使用MYSQLi访问在PHP中准备好的语句后插入的对象的id


Access the id of the object inserted after a prepared statement in PHP using MYSQLi

我需要最后插入对象的id。我使用预先准备好的语句来避免sql注入。但我不知道如何获得id。

$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name, 
               middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";
        if (!($stmt = $mysqli->prepare($sql)))
            echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
        $stmt->bind_param('sissssss', 
                $faculty['id'], 
                $faculty['term'], 
                $faculty['role'],
                $faculty->name->prefix,
                $faculty->name->first,
                $faculty->name->middle,
                $faculty->name->last,
                $faculty->name->suffix
        );
        if (!$stmt->execute())
            echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
        $result = $stmt->insert_id;
        echo "'n Result:" . $result;    
        $stmt->close();             

结果总是0,尽管数据库中有一个条目

解决方案正在将元素插入数据库中。问题是,当我创建表时,id不是整数,而是代表员工id的varchar。为了解决这个问题,我在表中添加了员工id作为附加列,并使用了默认的id int auto_increment主键,它起到了作用。

尝试将$result = $stmt->get_result();更改为$result = $stmt->insert_id;

get_result()更多地用于SELECT查询,而不是INSERT s。

http://php.net/manual/en/mysqli-stmt.get-result.php

http://php.net/manual/en/mysqli-stmt.insert-id.php