我正在创建一个使用PHP和MySQL的登录/注册页面,一切正常,但是当我尝试从MySQL检索insert_id时,它不起作用。即使我试图“打印”结果,它只会说1.继承我的代码:
这是我的联系:
<?
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);
}
}
?>
这是我的用户类:
<?
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;
}
}
?>
最后这就是我称之为INSERT的地方:
<?
Users::$result=NULL;
$c=Users::createUser("INSERT INTO users (user,password,lastLogin) VALUES ('$username_register','$password_register',NOW())");
echo Users::$result;
?>
正如我所说的,一切正常,我可以从数据库中获取记录,它可以正确插入等等,但是当我使用insert-id时,它只是什么都没有。
答案 0 :(得分:3)
您在insert_id
(mysqli_result
)的结果中呼叫mysqli::query
。你应该在mysqli
对象上调用它。
您必须重构代码。也许是这样的:
class Query extends Connection { //Query database
...
public static function lastInsertedId()
{
return parent::getInstance()->getConnection()->insert_id;
}
}
...
$c=Query::run($sql);
echo Query::lastInsertedId();