Jump to content

echo result from prepared statement function


slj90

Recommended Posts

$username = "user1";

$result = single_row_prepared($username);

echo $username . " - " . $country . " - " . $about . " - " . $age;

It says the variables are undefined. How do I echo them out?

  function single_row_prepared($username) {
global $connect;

$sql = "SELECT profile_username, profile_country, profile_about, profile_age ";
$sql .= "FROM profiles ";
$sql .= "WHERE profile_username = ?";
$stmt = mysqli_prepare($connect, $sql);


mysqli_stmt_bind_param($stmt, 's', $username);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $username, $country, $about, $age);

mysqli_stmt_fetch($stmt);
	
mysqli_stmt_close($stmt);
  }
  
[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: country in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13
[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: about in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13
[06-Dec-2017 08:19:54 UTC] PHP Notice:  Undefined variable: age in /home/buysnapchats/public_html/examples/prepared_statement_single_row.php on line 13

Link to comment
Share on other sites

Variables defined inside of a function are not available outside of a function. Return everything you need using an array.

 

"single_row_prepared" sounds like it can handle any query, but it can't. It's only about profiles. So name it in a way that shows it gets a profile. Like "get_profile".

function get_profile($connect, $username) {
	$sql = "SELECT profile_username, profile_country, profile_about, profile_age ";
	$sql .= "FROM profiles ";
	$sql .= "WHERE profile_username = ?";

	$stmt = mysqli_prepare($connect, $sql);

	mysqli_stmt_bind_param($stmt, 's', $username);

	mysqli_stmt_execute($stmt);

	mysqli_stmt_bind_result($stmt, $username, $country, $about, $age);

	mysqli_stmt_fetch($stmt);

	mysqli_stmt_close($stmt);

	return ["username" => $username, "country" => $country, "about" => $about, "age" => $age];
}
$username = "user1";

$result = get_profile($username);

echo $result["username"] . " - " . $result["country"] . " - " . $result["about"] . " - " . $result["age"];
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.