【发布时间】:2014-01-12 05:06:43
【问题描述】:
我正在重建我当前的脚本以支持 PDO 而不是 MySQL 查询。我被困在这个插入查询上,它没有执行,我不知道为什么。
Google 搜索了一下,但没有找到任何东西。
try
{
$sql = "INSERT INTO
news (news_name,
news_description,
news_author,
news_date,
news_link,
news_category)
VALUES ('" . trim($_POST['news_name']) . "',
'" . trim($_POST['news_description']) . "',
" . $_SESSION['admin_id'] . ",
NOW(),
'" . trim($_POST['news_link']) . "',
'" . trim($_POST['news_category']) . "'
)";
$results = $db->exec($sql);
$id = $db->lastInsertId();
if($results)
{
echo $id;
echo '<p>News item added succesfully</p>';
echo '<a href="admin.php">Click here to return to the admin panel</a>';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
【问题讨论】:
-
不要将值连接到您的查询中。阅读
PDO::prepare、PDOStatement::bindParam/PDOStatement::bindValue和PDOStatement::execute的文档和示例 -
另外,如果您希望它抛出异常,您需要将
PDO::ATTR_ERRMODE属性设置为PDO::ERRMODE_EXCEPTION。见PDO::setAttribute