0

I use prepared statements rather frequently to insert data, but I'm trying to select data and having an issue I can't seem to wrap my head around.

This code does not work at all. No error, just no results:

$student_name = "Student, Sample";
$student_number = "";

$SQLStmt = $db->prepare( "SELECT student_number FROM table WHERE `name` = ?" );
$SQLStmt->bind_param( "s", $student_name );
$SQLStmt->bind_result( $student_number );
$SQLStmt->execute();
$SQLStmt->store_result();
echo $student_number;

This code works just fine:

$student_name = "Student, Sample";
$student_number = "";

$SQLStatement = "SELECT student_number FROM table WHERE `name` = '".$student_name."'";
$result = $db->query($SQLStatement);
$myrow = $result->fetch_assoc();         
echo $myrow['student_number']; 

Any ideas would be most appreciated. Thanks!

Chris
  • 3
  • 1
  • To get errors out of PHP _even in a LIVE environment_ add these 4 lines **temporarily, while debugging**, to the top of any `MYSQLI_` based script you want to debug `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);`. This will force any `MYSQLI_` errors to generate an Exception that you can see on the browser as well as normal PHP errors. – RiggsFolly Jun 15 '22 at 15:27
  • Actually 3 of these lines should be permanent, and only display_errors should be switched on and off depends on the server role – Your Common Sense Jun 15 '22 at 16:17
  • @YourCommonSense Yea, I know, but having worked on code from dubious area's of the world, that always started by turning all error processing off because the code was so terriible. I now assume, rightly or wrongly, that its likely error processing is turned off so the dev's can move on to the billing phase before the client realises they bought a pig in a poke – RiggsFolly Jun 15 '22 at 16:22

1 Answers1

0

This does not fetch rows from the resultset

$SQLStmt->store_result();

Try instead

$student_name = "Student, Sample";
$student_number = "";

$SQLStmt = $db->prepare( "SELECT student_number FROM table WHERE `name` = ?" );
$SQLStmt->bind_param( "s", $student_name );
$SQLStmt->bind_result( $student_number );
$SQLStmt->execute();
$results = SQLStmt->get_results();
$row = $results->fetch_assoc();
echo $row['student_number'];
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Thank you! Of course...the Fetch Statement! I added $SQLStmt->fetch(); and now it works – Chris Jun 15 '22 at 16:07