updating records with prepared statements, checking if update worked

流过昼夜 提交于 2019-12-07 04:46:54

问题


I have a query that updates a record on my database, it works fine but i wanted to know how to check if the update has happened so i can return true and display the right message?

Now i know with a SELECT query i can do:

if(stmt->fetch())

If that is true i return true and saying "records found" but i haven't got a clue how to do it for an update query?

Anyone know how to?

$query = "UPDATE user
            SET password = ?
            WHERE email = ?";

if($stmt = $conn->prepare($query)) 
{
    $stmt->bind_param('ss', $pwd, $userEmail);
    $stmt->execute();

    //Check if update worked
}

Thanks for the help.


回答1:


check if below works

$query = "UPDATE user
        SET password = ?
        WHERE email = ?";

if($stmt = $conn->prepare($query)) 
{
$stmt->bind_param('ss', $pwd, $userEmail);
if ($stmt->execute()) 
{
// worked
} 
else 
{
// not worked
}

Good Luck!!!




回答2:


Execute method returns True when it finished successfully, but, if this behavior is not enough for you, you can check also for affected rows:

$query = "UPDATE user
            SET password = ?
            WHERE email = ?";

if($stmt = $conn->prepare($query)) 
{
    $stmt->bind_param('ss', $pwd, $userEmail);
    if ($stmt->execute()) {
        //query with out errors:
        printf("rows updateds: %d\n", $stmt->affected_rows);
    } else {
        //some error:
        printf("Error: %s.\n", $stmt->error);
    }
}

The second check you can do is to verify that exactly 1 row was updated:

if($stmt = $conn->prepare($query)) 
{
    $stmt->bind_param('ss', $pwd, $userEmail);
    if ($stmt->execute() and $stmt->affected_rows == 1) {
        //your update is succesfully.
    }
}



回答3:


From the manual for mysqli_stmt_execute()

Returns TRUE on success or FALSE on failure.




回答4:


Would the mysql_affected_rows() function work for you?




回答5:


If you are using PDO (it seems so...), you can check with rowCount:

$affected_rows = $stmt->rowCount();

And use a try - catch block for errors.




回答6:


A few years late, but perhaps this could help someone..

As others have mentioned already you can use affected_rows to check if the UPDATE query in a PREPARED STATEMENT has indeed updated any record. However, do note that if the submitted data is the same as the record in the database 'affected_rows' will return a zero (0).

A workaround of mine is creating a column for TIMESTAMP with ON UPDATE CURRENT_TIMESTAMP. Then every time I run the query, I'll also pass on a NULL value to the column tracking the time - that way forcing the row to UPDATE every time the query is executed. Then all you do is check for affected_rows.



来源:https://stackoverflow.com/questions/8927486/updating-records-with-prepared-statements-checking-if-update-worked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!