Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating records with prepared statements, checking if update worked

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.

like image 979
ragebunny Avatar asked Dec 22 '22 03:12

ragebunny


1 Answers

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.
    }
}
like image 120
dani herrera Avatar answered Dec 24 '22 01:12

dani herrera