Answer the question
In order to leave comments, you need to log in
How to check adding to database in PDO?
The subject is in the subject ...
I used to write like this:
if ( -1 !== mysql_affected_rows() ) {
echo 'Вы успешно зарегистрированы!';
} else {
echo 'Ошибка при регистрации';
}
$insertId=$db->lastInsertId();
Answer the question
In order to leave comments, you need to log in
Using lastInsertId to check if the insert succeeded or not is a bad idea.
Small example from php.net
Example on a new Row:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>
Above displays: 1
Expected display: 1
Example on an existing row that gets updated:
<?php
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
?>
Above displays: 2
Expected display: 1 (since no new records were inserted)
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$tmt->execute( array('user', '[email protected]'));
$dbh->commit();
print $dbh->lastInsertId();
} catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
} catch( PDOExecption $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
lastInsertId should be called when you have verified that the data has been written to the database. And you can make sure by simply checking that there were no errors when executing the request. mysql_affected_rows is not needed here, it is enough to check for errors after exec, or even better - tell PDO to throw exceptions and process them if something happens.
How to check adding to database in PDO?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question