updating records with prepared statements, checking if update worked

后端 未结 4 1840
一个人的身影
一个人的身影 2021-01-14 02:16

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 me

4条回答
  •  渐次进展
    2021-01-14 02:44

    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.
        }
    }
    

提交回复
热议问题