简体   繁体   English

获取最后插入ID的代码有什么问题?

[英]What's wrong with my code to get last insert id?

This is my code to insert date to database. 这是我在数据库中插入日期的代码。 Everything is fine except I cannot get insert_id. 一切都很好,除了我无法获取insert_id。

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    $data_to_store = filter_input_array(INPUT_POST);
    $db = getDbInstance();
    $Stats = $db->insert ('images', $data_to_store);
    $last_id = $db->insert_id();

    if($Stats)
    {
        $_SESSION['success'] = "Record added successfully!";
        header('location: index.php');
        exit();
    }  
}

It shows: 表明:

Fatal error: Uncaught Error: Call to undefined method MysqliDb::insert_id() in

My db: 我的数据库:

 function getDbInstance() { 
    return new MysqliDb(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME); 
 }

What's wrong? 怎么了?

Since PHP's class for mysqli is called mysqli , I'm guessing you're using PHP-MySQLi-Database-Class , whose class name is MysqliDb . 由于PHP的mysqli类称为mysqli ,因此我猜您正在使用PHP-MySQLi-Database-Class ,其类名为MysqliDb This information is important and missing in your post, superb! 这些信息非常重要,并且在您的帖子中也很少见!

If you take a look at the class, you'll see that there is no function called insert_id with 0 parameters. 如果您看一下该类,您会发现不存在带有0个参数的名为insert_id函数。 The function you're looking for is called getInsertId . 您要查找的函数称为getInsertId As found in the source . 正如在源中发现的那样。

From what I know MysqliDb does not have a last insert id function like you've tried : insert_id . 据我了解, MysqliDb没有像您尝试过的最后一个插入id函数: insert_id

There are two ways to go about it. 有两种解决方法。

  1. Change the library to avail something like this PDO::lastInsertId or 更改库以使用类似以下的PDO :: lastInsertId
  2. You can simply run a select query and fetch the last id in your table. 您只需运行选择查询并获取表中的最后一个ID。

insert_id is a property not a method so it should not have the parenthesis. insert_id是属性而不是方法,因此它不应该带有括号。 so it should be 所以应该

$last_id = $db->insert_id;

not

$last_id = $db->insert_id();

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

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