我一直在寻找其他提出同样问题的问题,但我不明白为什么我的查询不会表现得像它应该的那样。
我的问题是:
$stmt = db()->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo db()->lastInsertId();当我这样做的时候,lastInsertId();一直返回0。
我的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;
}发布于 2013-04-17 16:55:31
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;
}发布于 2013-04-17 16:56:54
每行都会创建一个新的数据库连接。
尝试:
$db = db();
$stmt = $db->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo $db->lastInsertId();https://stackoverflow.com/questions/16055671
复制相似问题