php - Mysqli->insert_id not returning anything
I'm creating a login/sign up page with PHP and MySQL, everything works just fine, but when I try to retrieve the insert_id from MySQL just doesn't work. Even if I try to "print" the result, it only says 1. Heres my code:
Here's my connection:
<?
class Connection { //Connect to database
/* Arguments */
private $_host = "localhost";
private $_username = ""; /* Change */
private $_password = ""; /* Change */
private $_database = "";
private $_connection;
private static $_instance;
/* Methods */
private function __construct(){ //Initial method
$this->_connection=new mysqli($this->_host,$this->_username,$this->_password,$this->_database);
if($this->_connection->connect_error){
trigger_error("Error al conectar a base de datos: " . $this->_connection->connect_error);
}
$this->_connection->set_charset("utf8");
}
private function __clone(){} //Magic method
public static function getInstance(){ //Get instance of connection
if(!self::$_instance){
self::$_instance=new self();
}
return self::$_instance;
}
public function getConnection(){ //Get MySQLi connection
return $this->_connection;
}
}
class Query extends Connection { //Query database
public static function run($sql){
return parent::getInstance()->getConnection()->query($sql);
}
}
?>
And here's my users class:
<?
class Users {
/* Arguments */
public static $result=NULL;
/* Methods */
public static function getDuplicated($sql){ //Get duplicated records
$d=Query::run($sql);
self::$result=$d->num_rows;
}
public static function createUser($sql){ //Create new user on database
$c=Query::run($sql);
self::$result=$c->insert_id;
}
}
?>
And finally this is where I call the INSERT:
<?
Users::$result=NULL;
$c=Users::createUser("INSERT INTO users (user,password,lastLogin) VALUES ('$username_register','$password_register',NOW())");
echo Users::$result;
?>
As I said, everything works just fine, I can get records from database, it inserts correctly and so on, but when I user insert-id, it just gives nothing.
Answer
Solution:
You are calling
insert_id
in the result ofmysqli::query
(which is). You should call it on the
object.
You'll have to refactor your code. Maybe something like: