Jump to content
Sign in to follow this  
slj90

echo result from prepared statement function

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

Share this post


Link to post
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"];

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

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.