获取准备好的查询状态中的插入 ID



我有一些PHP代码,可以在一些表中插入很多东西。

$token = bin2hex(openssl_random_pseudo_bytes(64));
$what = 'profilepicture';
$name = 'Profile picture';
$specs = '';
$add = '';
$insertion = $mysql->prepare("UPDATE users SET image = ? WHERE id = ?");
$insertion->bind_param('ss', $intheendtheimageuknowamk, $myid);
$add_photo_gallery = $mysql->prepare("INSERT INTO users_photos_galleries (uid,name,specs,timestamp,token) VALUES (?,?,?,?,?)");
$add_photo_gallery->bind_param('sssss', $myid, 'Profile images', '', $posted_on, $token);
$add_photo_gallery->execute();
$lastid_gallery = $add_photo_gallery->insert_id;
$add_photo = $mysql->prepare("INSERT INTO users_photos (uid,gid,path,name,specs,what,timestamp,token) VALUES (?,?,?,?,?,?,?,?)");
$add_photo->bind_param('ssssssss', $myid, $lastid_gallery, $intheendtheimageuknowamk, $name, $specs, $what, $posted_on, $token);
$add_photo->execute();
$lastid_photo = $add_photo->insert_id;
$add_log = $mysql->prepare("INSERT INTO users_logs (uid,what,relid,addition,timestamp,token) VALUES (?,?,?,?,?,?)");
$add_log->bind_param('ssssss', $myid, $what, $lastid_photo, $add, $posted_on, $token);
$add_log->execute();
echo $intheendtheimageuknowamk;

这似乎现在有效,但可能会发生一些错误,例如如果只有第二个查询无法插入,那么其余查询也不会插入,而是第一个查询。我尝试将每个查询放入 if 语句中,如果前一个查询的执行成功,则只与下一个查询交谈,但从逻辑上讲,这将是相同的结果。有没有其他方法可以解决这个问题?只是通过检查所有查询的执行来回显结尾名称也不起作用,因为我需要查询的last_insert ID,这实际上是我最大的问题。

不要使用 rowCount() 方法。此方法将返回查询产生的行数。

要查找最新插入的 Id,请使用$id = $mysql->lastInsertId();

最新更新