Reputation: 1146
I have the following query:
$query = "UPDATE list SET locked=1, @id:=id WHERE worked=0 and is404=0 AND error=0 AND locked=0 LIMIT 1;SELECT * FROM list WHERE id=@id;";
$stmt = $pdo->prepare($query);
if ($stmt->execute()) {
$model = $stmt->fetch(PDO::FETCH_OBJ);
if ( isset($model) && !isset($model->id) ) {
echo json_encode(array('error' => -1, 'type' => 'No URL'));
exit;
}
}
What I'm trying to accomplish is to lock a row using one of its fields called 'locked' and thus avoiding other parallel process intefer among them.
If I run the query in console, it works fine and returns the locked row by the @id used in the UPDATE.
The problem comes when using PDO in php. the row get locked but the SELECT statement does not return anything.
What's wrong in my code?
Upvotes: 0
Views: 135
Reputation: 157872
This is not a single query but two queries
$pdo->query("UPDATE list SET locked=1, @id:=id WHERE worked=0 and is404=0 AND error=0 AND locked=0 LIMIT 1");
$stmt = $pdo->query("SELECT * FROM list WHERE id=@id");
$model = $stmt->fetch(PDO::FETCH_OBJ);
That said, the locking model you choose is unreliable, two parallel processes could return the same id
Upvotes: 1