I am updating a row in a table, and trying to return the updated row, as per this SO answer.
My code is the following:
$sql = \"SET @update_id := \'\
You need to do the SELECT @update_id
as a separate query -- you can't put multiple queries in a single statement. So do:
$sql = "SET @update_id := '';
UPDATE testing SET status='1', id=(SELECT @update_id:=id)
WHERE status='0' LIMIT 1";
try{
$db->beginTransaction();
$db->query($sql); // no need for prepare/execute since there are no parameters
$stmt = $db->query("SELECT @update_id");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $row['@update_id'];
$db->commit();
} catch (Exception $e) {
echo $e->getMessage();
$db->rollBack();
exit();
}
You're right about getting the exception SQLSTATE[HY000] for $stmt->rowCount();
The problem is, you cannot fetch an UPDATE query because these queries simply don't return values. To circumvent this, use rowCount().
As written in the PHP documentation, PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.
Check out this example.
<?php
/* Updating rows from the PICNIC table*/
$update = $dbh->prepare('UPDATE ... PICNIC');
$update->execute();
/* Return the number of rows affected */
echo $updateCount = $update->rowCount();
?>
It's failing on ->fetchAll()
because an UPDATE
query does not return any rows/data.
What you want to do, is check out PDO::rowCount(). This returns the count of how many rows have been affected by your query.
echo $stmt->rowCount();
This was posted assuming you're trying to check if your query was successful.