insert_id 的值不断返回 0

Value of insert_id keeps returning 0

我正在尝试创建一个注册表单,希望让用户知道其 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;
    }
}

基础问题

多次使用:$this->database()

它每次都会创建新的连接,这就是为什么它总是返回 0:

正确代码:

public function checkEmpty($fname, $lname, $num, $email, $gettype)
{
    $this->fname = $fname;
    $this->lname = $lname;
    $this->num = $num;
    $this->email = $email;
    $this->gettype = $gettype;
    $db = $this->database();
    $sql = "INSERT INTO User(firstname, lastname, phone, email, type) VALUES ('$this->fname', '$this->lname', '$this->num', '$this->email', '$this->gettype')";

    if($db->query($sql)!==false)
    {
        $last_id = $db->insert_id;
        echo "<h3>Congratulations ". $this->fname. " " .$this->lname. ", account successfully registered</h3>";

        echo "Your ID Number is " . $last_id;
    }
 $db->close(); //close db connection too it's very important
}

注:

a) 您的脚本在 MYSQLI_PDO API 中对 SQL Injection Attack. You should always use prepared parameterized statements 开放,而不是将用户提供的值连接到查询中。永远不要相信任何用户输入!

b) $conn->close();return $conn; 之后是不必要的。

c) 确保在使用结束后关闭连接(在您使用的每个功能中)