I have a PDO statement that for some reason refuses to execute properly. It returns false. However, when running the exact same statement using PDO’s query(), it works like it should . . .
This is the relevant code:
// Prepare PDO statement
$getStatus = $dbHandle->prepare("SELECT `active` FROM `teachers`
WHERE `id` = :teacher LIMIT 1;");
$getStatus->setFetchMode(PDO::FETCH_ASSOC);
$getStatus->bindParam(':teacher', $teacher_id, PDO::PARAM_INT);
// This statement retrieved the relevant teacher id;
// or false, if an invalid teacher was specified; in this
// case, we specify a valid teacher
$teacher_id = array_search($_POST['teacherName'], $acronyms);
// For debugging: show $teacher_id
echo("$teacher_id<br />");
// Execute query; should return an associative array
$newStatusArray = $getStatus->fetch();
// Nothing . . .
print_r($newStatusArray);
// returns "bool(false):
var_dump($newStatusArray);
// Trying with a query
foreach ($dbHandle->query("SELECT `active` FROM `teachers`
WHERE `id` = $teacher_id LIMIT 1;") as $row) {
// This loop runs only once because of the LIMIT 1
$newStatus = $row['active'];
}
// This prints the new status (was changed before, is always 0 or 1)
echo("$newStatus<br />");
The normal query, although it should do exactly what the prepared statement does, works; but the prepared statement returns nothing . . .
$getStatus->errorCode() is empty . . . So MySQL is happy. Also, $getStatus->debugDumpParams() shows what it’s supposed to:
SQL: [62] SELECT `active` FROM `teachers` WHERE `id` = :teacher LIMIT 1;
Params: 1 Key: Name: [8] :teacher paramno=-1 name=[8] ":teacher"
is_param=1 param_type=1
I have been trying to get this to work for over an hour now, but I seriously don’t get what’s going wrong. Can anybody see what’s the problem here?
I would greatly appreciate any pointers!
/////////////////////////////////////////////// EDIT: ///////////////////////////////////////////////
Thank you for your answers! So stupid – indeed, I had forgotten the execute statement. Duh . . . Very, very embarassed. Sorry for having taken up your time with this!!! Like this, it does work:
if (!$getStatus->execute()) {
errorHandler("Errorcode: {$getStatus->errorCode()},
errorinfo: {$getStatus->errorInfo ()}.");
}
$newStatusArray = $getStatus->fetch();
var_dump($newStatusArray);
The bindParam can stay at the top; which is in line with my understanding of the value of this method; you can just designate a variable to a slot in the PDO statement, and the whenever the query is executed, the value of the variable at that moment is passed along.
You forgot to actually
->execute()your statement.