我正在尝试创建一个注册表单,我希望让用户知道他的 ID 的值。我能够成功注册用户,但即使数据库中有多行,insert_id 仍然返回 0。
数据库
public function database()
{
$this->servername = "localhost";
$this->username = "root";
$this->password = "";
$this->dbname = "dba3";
$conn = new mysqli($this->servername, $this->username,$this->password,$this->dbname);
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$this->tablename = "User";
$checktable = $conn->query("SHOW TABLES LIKE '$this->tablename'");
$table_exists = $checktable->num_rows >= 1;
if(!$table_exists) {
$sql = "CREATE TABLE $this->tablename(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
phone VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
type VARCHAR(20) NOT NULL)";
if($conn->query($sql)===TRUE){
echo "Table sucessfully created";
} else {
echo "Error creating table: " . $conn->error;
}
}
return $conn;
$conn->close();
}
PHP 代码
public function checkEmpty($fname, $lname, $num, $email, $gettype)
{
$this->fname = $fname;
$this->lname = $lname;
$this->num = $num;
$this->email = $email;
$this->gettype = $gettype;
$sql = "INSERT INTO User
(firstname, lastname, phone, email, type)
VALUES ('$this->fname', '$this->lname',
'$this->num', '$this->email', '$this->gettype')";
if($this->database()->query($sql)!==FALSE) {
$last_id = $this->database()->insert_id;
echo "<h3>Congratulations ". $this->fname. " " .$this->lname. ", account successfully registered</h3>";
echo "Your ID Number is " . $last_id;
}
}