Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 读取最后插入的行_Php_Mysql_Transactions_Pdo - Fatal编程技术网

Php 读取最后插入的行

Php 读取最后插入的行,php,mysql,transactions,pdo,Php,Mysql,Transactions,Pdo,我有以下插入语句 global $dbUser; global $dbPW; $query = "INSERT INTO comments (post_id, text) VALUES (:post_id,:text)"; $db = new PDO('mysql:host=localhost;dbname=test', $dbUser, $dbPW); $statement = $db -> prepare($query); $statement -> execute(array(

我有以下插入语句

global $dbUser;
global $dbPW;
$query = "INSERT INTO comments (post_id, text) VALUES (:post_id,:text)";
$db = new PDO('mysql:host=localhost;dbname=test', $dbUser, $dbPW);
$statement = $db -> prepare($query);
$statement -> execute(array(':post_id' => $postId, ':text' => $text));
我想在同一事务中读取并返回插入的行

我知道我能得到那份工作

$db->lastInsertId('id')

但是,我知道如何在PDO中执行事务,但我无法找到如何使用如上所述的准备好的语句来执行事务(出于安全目的,这是IIRC的首选方法)


谢谢

这里不需要任何交易。

如果需要自动生成id,只需运行$db->lastInsertId()。

顺便说一句,您不应该在函数中连接。每个应用程序连接一次,然后在整个代码中使用一次连接。@YourCommonSense ok谢谢,这意味着“$db=new PDO('mysql:host=localhost;dbname=test',$dbUser,$dbPW);”将被初始化一次(比如在我的全局include文件中),并重新用作全局变量?是的,没错。只需将其设置为
global$db。否则,您将从单个脚本执行中向数据库服务器发送多个连接的垃圾邮件。在这种情况下,这是真的,在其他情况下,我在select语句中有公式,我不想在代码的其他部分再次使用。谢谢你的宝贵意见!!