Getting Insert and Update ID with PDO

I am trying to get mysql_insert_id using PDO. So far, I have not found a good example that works with both insert and update. Does anyone have complete code as an example?

+3
source share
3 answers

If you need $pdo->lastInsertId() to return the id of the just updated line (I would seriously rethink my design if I needed it, but hey ... maybe a real need), do the update like this:

  UPDATE tablename SET some_column='somevalue',id=LAST_INSERT_ID(id); 
+8
source

PDO :: lastInsertId . Returns the identifier of the last inserted row or sequence value

+3
source
 <?php try { $dbh = new PDO('mysql:host=localhost;dbname=test', 'usrname', 'passwrd'); $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?);"); try { $dbh->beginTransaction(); $stmt->execute( array('user', ' user@example.com ')); $dbh->commit(); print $dbh->lastInsertId(); } catch(PDOExecption $e) { $dbh->rollback(); print "Error!: " . $e->getMessage() . "</br>"; } } catch(PDOExecption $e) { print "Error!: " . $e->getMessage() . "</br>"; } ?> 
0
source

Source: https://habr.com/ru/post/948843/


All Articles