mysql\u insert\u id()和last\u insert\u id不起作用

pb3skfrl  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(468)

我在最近的macbookpro上使用mysql/php/apache,所有请求都发送到localhost。我已经找过了,但找不到解决问题的办法。
我的php脚本成功地将一条记录插入到一个基本主表中,该表的主键名为id,是一个自动递增字段,但当我尝试使用last\u insert\u id()或sql\u insert\u id()时,它无法捕获该id的值,以便与另一个插入到不同表中的内容一起使用。第二个表所需的数据只需要该值和来自同一html表单的文本字段的内容。
毫无疑问,如果我在等号后面加上一个整数(作为测试),我的脚本就可以完美地工作(也就是说,没有错误,而且脚本将所需的数据完美地输入到第二个表中)。我尝试了sql\u insert\u id()和last\u insert\u id(),得到了相同的结果:一个完全白色的屏幕。
没有外键约束或任何复杂的东西。此代码失败并返回一个白色屏幕:

$sql = "INSERT INTO Table1 
    (int1, str1, int2, int3, int4, int5) 
    VALUES (?, ?, ?, ?, ?, ?)";

if($stmt = mysqli_prepare($link, $sql)){
    mysqli_stmt_bind_param($stmt, "isiiii", 
        $param_int1, $param_str1, $param_int2, 
        $param_int3, $param_int4, $param_int5);
}

if(mysqli_stmt_execute($stmt)){
    $last_id = sql_insert_id();        // <--- problem statement
} else {
    echo "Something went wrong with the execution.";
}

但当我使用整数代替所讨论的函数时,代码的工作方式与我希望的完全一样:

if(mysqli_stmt_execute($stmt)){
    $last_id = 6;
} else {
    echo "Something went wrong with the execution.";
}

如果第一次插入成功,if(mysql\u stmt\u execute($stmt))将返回true,因此在这之后初始化变量$last\u id似乎是合乎逻辑的。这样可以吗?我还能在哪里查看我的代码?我需要在函数的括号内提供数据吗?
mysql版本是5.7.21 mac os x版本10.13.4
我认为自己是php/mysql的初学者。任何帮助都将不胜感激。

6ie5vjzr

6ie5vjzr1#

尝试

mysqli_insert_id($link);

我觉得你把oop和库的过程部分搞混了。
因为如果我没记错的话 sql_insert_id 是从现在不存在的 mysql_* 图书馆。
https://www.w3schools.com/php/func_mysqli_insert_id.asp

相关问题