[英]PDO lastInsertId() returns 0
I've been looking, at other questions asking the same, and can't figure out why my query won't act like it should. 我一直在问其他同样的问题,却无法弄清楚为什么我的查询不会像预期的那样起作用。
My query: 我的查询:
$stmt = db()->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo db()->lastInsertId();
When I do this the lastInsertId(); 当我这样做时,lastInsertId(); keeps returning 0.
继续返回0。
My db() function: 我的db()函数:
function db()
{
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
try {
$db = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
// exceptions handles here
}
return $db;
}
function db()
{
static $db;
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
if (!$db) {
$db = new PDO($dsn, $username, $password);
}
return $db;
}
You're creating a new db connection every line. 您正在每行创建一个新的数据库连接。
Try: 尝试:
$db = db();
$stmt = $db->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo $db->lastInsertId();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.