-2

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

我得到的输出示例

4

1 回答 1

3

基础问题

多次使用:$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) 您的脚本对SQL Injection Attack开放。您应该始终在或API 中使用准备好的参数化语句,而不是将用户提供的值连接到查询中。永远不要相信任何用户输入!MYSQLI_PDO

b) $conn->close();afterreturn $conn;是不必要的。

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

于 2021-02-11T09:14:29.133 回答