简体   繁体   English

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

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

I need the id of the last inserted object. 我需要最后插入对象的id。 I use prepared statements to avoid sql injection. 我使用预准备语句来避免sql注入。 But i'm not sure how to obtain the 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();             

The result is 0 always despite there being an entry in the database 尽管数据库中有条目,但结果始终为0

Solution The element was being inserted into the database. 解决方案该元素正在插入数据库中。 The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. 问题是,当我创建表时,id不是一个整数,它是一个表示员工ID的varchar。 To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked. 为了解决这个问题,我将employee id添加为表中的附加列,并使用默认id int auto_increment主键,并且它工作正常。

Try changing $result = $stmt->get_result(); 尝试更改$result = $stmt->get_result(); to $result = $stmt->insert_id; to $result = $stmt->insert_id;

get_result() is more for SELECT queries, rather than INSERT s. get_result()更适用于SELECT查询,而不是INSERT

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM