繁体   English   中英

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

[英]What's wrong with my code to get last 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();
    }  
}

表明:

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

我的数据库:

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

怎么了?

由于PHP的mysqli类称为mysqli ,因此我猜您正在使用PHP-MySQLi-Database-Class ,其类名为MysqliDb 这些信息非常重要,并且在您的帖子中也很少见!

如果您看一下该类,您会发现不存在带有0个参数的名为insert_id函数。 您要查找的函数称为getInsertId 正如在源中发现的那样。

据我了解, MysqliDb没有像您尝试过的最后一个插入id函数: insert_id

有两种解决方法。

  1. 更改库以使用类似以下的PDO :: lastInsertId
  2. 您只需运行选择查询并获取表中的最后一个ID。

insert_id是属性而不是方法,因此它不应该带有括号。 所以应该

$last_id = $db->insert_id;

$last_id = $db->insert_id();

暂无
暂无

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

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