使用过程插入行时 PHP MYSQL PDO lastInsertId 返回 0

标签 php mysql pdo last-insert-id

我的 LastInsertedID 一直为零,我认为这是因为我正在使用 mysql 存储过程。这是我的代码:

// Set up a new MYSQL PDO Database Connection
$dbConnection = new PDO('mysql:host=localhost;dbname=database;charset=UTF8', 'username', 'password');
//turn off emulation for prepared statement and set error mode option
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//Create a statement and prepare it with parameters
$stmt = $dbConnection->prepare("CALL AddMovieSet(:UserID, :SelectedLibraryID, :txtName, :txtNotes);");
$stmt->bindValue(':UserID', $_SESSION["UserID"], PDO::PARAM_STR);
$stmt->bindValue(':SelectedLibraryID', $_SESSION["SelectedLibraryID"], PDO::PARAM_STR);
$stmt->bindValue(':txtName', $_GET["txtName"], PDO::PARAM_STR);
$stmt->bindValue(':txtNotes', $_GET["txtNotes"], PDO::PARAM_STR);
//execute the prepared statement
$stmt->execute();

//the stored procedure successfully inserts a row
$Name=$_GET["txtName"];
$Notes=$_GET["txtNotes"];
$InsertedID=$dbConnection->lastInsertId(); 
//$InsertedID is always zero, the table I am inserting a row into has an AUTO_INCREMENT for the first column.

最佳答案

有时 PHP 和 PDO 可能会因 lastInsertID() 和存储过程而出现错误。尝试使用此 MySQL 调用:

"SELECT LAST_INSERT_ID();"

关于使用过程插入行时 PHP MYSQL PDO lastInsertId 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562478/

相关文章:

php运行一次并在mysql数据库中插入两次

php - 从查询转换为 Yii2 的 ModelSearch

php - UPSERT BigQuery

PHP登录功能找不到正确的用户名和密码

php - 比较同一个表中的两个值

c# - 我的一张表没有显示在模型图中 EF5.0 VS 2013 Community

MySQL WHERE NOT EXISTS 错误

php - 从 magento 模块创建一个新表

PHP MYSQL 列数据下拉列表

PHP - 所有 PDO 事务和严格的 MySQL 事务之间的区别?