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

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

我需要最后插入的对象的ID。我使用准备好的语句来避免SQL注入。
但我不确定如何获取ID。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$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"\
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/zh/mysqli-stmt.get-result.php

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