Reputation: 9293
jquery-ajax sends post request to update database.
target.php:
$_POST = array_map( 'stripslashes', $_POST );
extract($_POST);
try {
$stmt = $db->prepare('UPDATE members SET logged = :logged WHERE user = :user') ;
$stmt->execute(array(
':logged' => 1,
':user' => $user,
));
echo ('WELCOME ' . $user . ' !');
}
catch(PDOException $e) {
echo $e->getMessage();
}
This works in any case, but it shouldn't work if - for example - given user does not exist in database.
How can I get one echo if database is really updated, or at least, if user really exists, and another echo if it does not?
Upvotes: 1
Views: 1623
Reputation: 780724
You can use $stmt->rowCount()
to find out if any rows were updated. It will be 0
if no rows were found, otherwise it will be non-zero.
if ($stmt->rowCount() == 0) {
echo "User $user not logged";
}
However, this will also return 0
if rows were found but there was nothing to change, because the value of logged
is already the new value you tried to assign.
Upvotes: 2
Reputation: 330
You can check if the user exists (SELECT * FROM members WHERE user = :user) before you make the update request.
If you want to do it without checking if the user exists, use $stmt->rowCount() after $stmt->execute(...) in order to really determine how many records has been changed. Also, the function $stmt->execute(...) returns true on success and false on failure.
Upvotes: 3