Get last id after insert (always return 0)
I have a Sql class like this:
class Sql extends PDO {
private $connection;
public function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=myDB", "root", "root");
}
(...)
Then I am trying to insert data into my db using another user.php class. Using getConection method (sql class method). Like this:
class User {
private $iduser;
private $deslogin;
private $despassword;
private $datecad;
(getters & setters)
public function insert() { //query & select are a SQL class method
$sql = new Sql();
$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS))", array(
':LOGIN'=>$this->getDeslogin(),
':PASS'=>$this->getDespassword()
));
echo $sql->getConnection()->lastInsertId(); //getConnection is a Sql Class method that returns the private connection.
}
Why is my echo always returning 0?
+3
source to share
1 answer
This is because you need the same connection object regarding the insert request to get the last inserted ID , but you create a new connection to get the last inserted ID. This is why you always get a result of 0.
See link:
http://php.net/manual/en/pdo.lastinsertid.php#120618
EDIT
From your code, link to your problem in insert
. You will note that there is one extra closing parenthesis
change your code to:
$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS)", array(
':LOGIN'=>$this->getDeslogin(),
':PASS'=>$this->getDespassword()
)); //<------there must be only one bracket after::LOGIN, :PASS
+4
source to share