I have an 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'm trying to insert a data in my db using another class "user.php". Using the "getConection" (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 my echo always returns 0?
Its because you need same connection object regarding insert query to get last inserted ID but you are creating new connection for getting last inserted ID. That's why you are always getting 0 as result.
See the reference :
http://php.net/manual/en/pdo.lastinsertid.php#120618
EDIT
From your code reference its problem in your insert Have you mark there is one extra closing bracket
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With