简体   繁体   中英

MySQL - Locking a row using UDPATE&SELECT - PDO in php

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM