I'm trying to update some code and update my coding skills at the same time. After looking at prepared statements on a few sites I tried turing this into a prepared statement:
$db=new Database();
$query='SELECT * FROM `student` WHERE `student_id`="'.$student_id.'" LIMIT 1';
$result=$db->query($query)or die('...');
$row=$result->fetch_assoc();
As an "easy" first step, I tried using a prepared statement without any variables because I seem to be hopelessly stuck on a elementary level:
$db = new mysqli("localhost", "uname", "pword", "astro8_gakkou");
if(!($stmt=$db->prepare("SELECT * FROM `student` WHERE `student_id`=5 LIMIT 1"))){
echo "Prepare failed: (".$db->errno.") ".$db->error;
}
if(!$stmt->execute()){
echo "Execute failed: (".$db->errno.") ".$db->error;
}
$result=$stmt->get_result();
$row=$result->fetch_assoc();
This kills php in it's tracks. It's the last line that's the culprit, but I can't understand why. I know I'm just being dumb, but can someone point to what fundamental concept I'm missing? I've read through php.net along with a host of other sites and I just can't seem to see what step I'm missing.
UPDATE: still not working, but I've updated the code. The log shows this error now:
[14-Mar-2014 22:34:10 America/New_York] PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /webdocs/zinc/class.Student.inc on line 38
It looks like you're missing a $result = $stmt->get_result();
Then pull the results $row = $result->fetch_assoc();
Checkout the first user-contributed-note here: http://www.php.net/manual/en/mysqli.prepare.php
The answer, despite my proclamations otherwise, was to use PDO. In it's simplest form this:
$db=new Database();
$query='SELECT * FROM `student` WHERE `student_id`="'.$student_id.'" LIMIT 1';
$result=$db->query($query)or die('...');
$row=$result->fetch_assoc();
Became this (using PDO and prepared statements):
$db=new PDO("mysql:dbname=school;host=localhost","root","root");
$stmt=$db->prepare("SELECT * FROM `student` WHERE `student_id`= ? LIMIT 1");
$stmt->bindParam(1,$student_id);
$stmt->execute();
$row=$stmt->fetch();
Huge thanks to the folks that pushed me (yelling and screaming) to use PDO. This works wonderfully and doesn't throw a single error. It'll mean a bit more work updating the code, but I'm thinking it'll be worth it in the long run.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.