PHP, MySQL, PDO - Get result from UPDATE query?

后端 未结 3 1442
说谎
说谎 2020-12-20 11:29

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 := \'\         


        
3条回答
  •  悲哀的现实
    2020-12-20 12:09

    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();
    }
    

提交回复
热议问题