php - Mysqli 最后插入 id 不起作用

标签 php mysql mysqli

我正在尝试获取最后一个查询插入 ID。但我的代码总是返回零。

我的代码

private function Cnn()
{
    return mysqli_connect('localhost','root','root','db');
}
protected function MyCommandInsertId($sql)
{
    if(mysqli_query($this->Cnn(),$sql))
    {
        return mysqli_insert_id($this->Cnn());
    }
    $this->err = mysqli_error($this->Cnn());
    return false;
}

public  function Insert()
{

        $sql = "insert general_info(name,email,password)
        values('".$this->ms($this->name)."','".$this->ms($this->email)."','".md5($this->password)."')";
        //print''.$sql.'';

        $last_insert_id=$this->MyCommandInsertId($sql);

}

这里返回 mysqli_insert_id($this->Cnn()); 总是返回零

最佳答案

请检查mysqli_insert_id的定义:-

mysqli_insert_id() 函数返回在最后一个查询中使用的 id(使用 AUTO_INCREMENT 生成)。

这意味着您的表中具有 AUTO_INCREMENT 值的列不存在。

或者

在当前程序流中,不会以编程方式在您的表上插入数据。由于您的代码中没有触发插入查询,因此它返回了

注意:- 只需先在您的代码中执行插入查询,然后检查 mysqli_insert_id 给出的输出是什么。然后你就可以很容易地理解我想说的了。谢谢

我本地的一个工作示例在这里:-

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
function Cnn()
{
    $conn = mysqli_connect('localhost','root','','stack');
    return $conn;
}
function MyCommandInsertId($sql)
{
    $conn = Cnn();
    if(mysqli_query($conn,$sql))
    {
        $lastid = mysqli_insert_id($conn);
        return $lastid;
    }else{
        $err = mysqli_error($conn);
        return $err;
    }

}
function Insert()
{
        $sql = "INSERT INTO bom(bom_description,product_id,finish_product,bom_quantity,UOM) values('Table cleaner','','','','')";
        $st_insert_id = MyCommandInsertId($sql);

        echo $st_insert_id;

}
Insert();
?>

输出:- http://prntscr.com/9u2iyv (插入的 ID)和 http://prntscr.com/9u2j6i(table插入后查看)

关于php - Mysqli 最后插入 id 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972286/

相关文章:

PHP,禁用自动输入[]到数组

php - 如何加载静态配置信息

php - 在数据库中插入和更新多行的最佳实践

php - 我错过了什么,一直给成员函数调用错误?

Mysql:显示不包含另一个表中的文本模式的查询结果

php - mysqli_fetch_array() 还是 mysqli_fetch_all()?

php - SSL 重定向 .htaccess 不工作

php - Laravel 5 验证修剪

php - 为什么 MySQL 的 UNIX_TIMESTAMP 在 MySQL 5.5 中返回奇怪的值,如 '%qd'?

php - 基于具有空单元格的数据库创建表