通过 PHP 使用 LAST_INSERT_ID() ?
当我在 MySQL 控制台中执行以下命令时,它工作正常:
INSERT INTO videos (embed_code) VALUES ('test code here');
SELECT LAST_INSERT_ID();
但是,当我通过 PHP 执行上述查询时,结果为空。
在数据抽象下,我使用名为 DB
的数据库访问类。这就是我通过 PHP 尝试上述查询的方法:
$embedCode = htmlentities($_POST['embed_code']);
//Insert video in database **WORKS**
DB::query("INSERT INTO videos (embed_code) VALUES ('$embedCode');");
//Retrieve id **DOES NOT WORK**
$row = DB::getSingleRow("SELECT LAST_INSERT_ID();");
$videoId = $row[0];
通过 embed_code 选择新 id 对我来说并不可靠,因为 embed_code 可能会重复。
谢谢!
When I execute the following in the MySQL console, it works fine:
INSERT INTO videos (embed_code) VALUES ('test code here');
SELECT LAST_INSERT_ID();
But, when I execute the above queries via PHP, the result is empty.
Under the data abstraction, I am using a database access class named DB
. This is how I have tried the above queries via PHP:
$embedCode = htmlentities($_POST['embed_code']);
//Insert video in database **WORKS**
DB::query("INSERT INTO videos (embed_code) VALUES ('$embedCode');");
//Retrieve id **DOES NOT WORK**
$row = DB::getSingleRow("SELECT LAST_INSERT_ID();");
$videoId = $row[0];
It is not reliable for me to select the new id by the embed_code, as the embed_code could be repeated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您的数据库类没有包含获取最后一个插入 ID 的函数吗?否则尝试 mysql_insert_id() 。
http://nl.php.net/mysql_insert_id
Doesn't your database class contain a function to grab the last insert ID? Try mysql_insert_id() otherwise instead.
http://nl.php.net/mysql_insert_id
PHP 有一个名为
mysql_insert_id
的函数,它会给出与查询SELECT LAST_INSERT_ID();
相同的结果。PHP has a function called
mysql_insert_id
which will give you the same result as the querySELECT LAST_INSERT_ID();
.有专门的函数用于此 - 您不应该使用 SQL 版本,因为它不起作用。
在 MySQL 库中,您应该使用 mysql_insert_id 函数,而 mysqli 对象有一个 insert-id财产。当然,这可能已经在您使用的任何数据库类中公开。
There are dedicated functions for this - you shouldn't be using the SQL version as it doesn't work.
In the MySQL library you should use the mysql_insert_id function, whereas the mysqli object has an insert-id property. This of course may already be exposed in whatever DB class you're using.
您可以尝试使用 PHP 的
mysql_insert_id
< /a> 函数。我认为发生的情况是每个
DB::query
调用都在不同的事务中,因此,$row
为空。也许您可以阅读 DB:query 文档来尝试在同一事务中运行这两个调用。You can try with PHP's
mysql_insert_id
function.I think what's happening is that each
DB::query
call is in a different transaction, hence,$row
is being empty. Maybe you can readDB:query
documentation to try running both calls within the same transaction.mysql_insert_id 已弃用。所以我认为这个线程需要更新。
mysql_insert_id is deprecated. So I think this thread needs to be updated.
自 PHP 5.5.0 起,mysql_insert_id 被标记为已弃用。
在此示例中,uid 是表视频的主键。
mysql_insert_id is marked as deprecated since PHP 5.5.0.
In this example uid is the primary key of the table videos.
您应该将 PDO 的 lastInsertId 返回到类的外部。例子:
you should return lastInsertId of PDO to outer of your class . example: