slj90 Posted December 6, 2017 Share Posted December 6, 2017 $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 Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted December 6, 2017 Solution Share Posted December 6, 2017 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"]; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.