我正在尝试从数据库获取新插入的记录ID,但始终返回0值。 在数据库中,我有2条记录,所以当我插入新记录时,我想要新记录ID 3,但我得到0。 在我的代码下面,我尝试获取ID
<?php
class User extends Database{
public function candidateRegister($name,$email,$pass){
$data = '';
$query = $this->connect()->query("INSERT INTO user(username, useremail, userpass) VALUES('$name','$email','$pass')");
if($query == true){
$data = $this->connect()->insert_id;
}else{
$data = 'Something went wrong';
}
return $data;
}
}
?>
在我的数据库连接代码下面
<?php
class database{
private $servername;
private $username;
private $password;
private $dbname;
protected function connect(){
$this->servername = 'localhost';
$this->username = 'root';
$this->password = '';
$this->dbname = 'mytable';
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
return $conn;
}
}
?>
答案 0 :(得分:-2)
确保表中有自动递增和主键。