我正在尝试使用以下代码删除数据库中的条目。 javascript函数将我带到index.php?delpost=
并使用正确的“adventureID”,但是当我检查我的数据库时,该行仍然存在。我最近开始使用PDO,所以我想知道execute()
语句是否可能是问题。 $ dbh连接到页面顶部的数据库,它正在工作,因为它打印表中的每一行我试图从中删除行。我的目标是在调用javascript函数时成功删除一行。问题是 - 它没有。
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
<a href="javascript:delpost('<?php echo $row['adventureID'] ?>','<?php echo $row['title'] ?>')">Delete</a>
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
答案 0 :(得分:0)
可能您遇到 MYSQL SAFE UPDATES 开启的问题。要避免它并最终删除行,您可以采取以下策略:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
要检查您是否已启用SQL_SAFE_UPDATES
,您可以执行以下操作:
SHOW VARIABLES LIKE 'sql_safe_updates'
答案 1 :(得分:0)
尝试替换此代码:
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
通过以下方式:
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
说明:
可在此处找到完整示例:http://php.net/manual/fr/pdostatement.execute.php#example-1050