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

后端 未结 3 1421
说谎
说谎 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();
    }
    
    0 讨论(0)
  • 2020-12-20 12:19

    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();
    
    ?>
    
    0 讨论(0)
  • 2020-12-20 12:22

    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.

    0 讨论(0)
提交回复
热议问题