【发布时间】:2021-05-15 00:18:14
【问题描述】:
我正在尝试创建一个注册表单,希望让用户知道其 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;
}
}
【问题讨论】:
-
您尝试过什么调试问题?另外,请注意,您的代码对 SQL 注入是广泛开放的
-
另外:在
return $conn之后调用任何东西都是没有意义的,因为 return 语句之后的代码不会被执行 -
你打电话给
if($this->database()->query($sql)!==FALSE)然后你打电话给$last_id = $this->database()->insert_id;,这里发生了什么?每当您调用$this->database()时,您都会创建一个新的mysqli实例。因此,新实例不知道您之前执行了另一个查询。 -
您在查看为什么会出现此错误时删除了关键细节。
-
@DefinitelynotRafal 我把它放回去修改
标签: php mysqli mysql-insert-id insert-id