我正在创建一个博客网站,我陷入了这个阶段,我想让作者删除他们自己的帖子,他们已经可以看到每个帖子下面的删除按钮了。在数据库表中,我有文章的作者,内容和ID。现在我需要获取他们想要删除的文章的特定ID,但我不知道如何执行此操作,删除按钮对于每篇文章都是相同的,因此我无法使用它来获取帮助。我有这个代码从我的数据库和按钮点击代码准备好的文章。为了更好的想象,这里是网站的图像 -
... previous code
<?php }
$articles->ArticlesConn();
$result = mysql_query("SELECT * FROM articles_table");
while($row = mysql_fetch_array($result)){ // loop to generate content
?>
<div class="container"> // responsive stuff
<div class="row"> // responsive stuff
<div class="twelve columns"> // responsive stuff
<?php
echo "<h3>" . $row['Title'] . "</h3>
<p>" . $row['Content'] . "</p>"; ?>
</div>
</div>
<div class="row">
<div class="eight columns">
<address><?php echo "Author - " . $row['Author']; ?> </address><br><br><br> /// nick of the author below each article
</div>
<div class="four columns">
<?php
if ($row['Author'] == $_SESSION["username"]) // show delete button if the logged user is an author of generated article
{ ?>
<input type="button" name="delete" value="Delete article"/>
<?php } ?>
</div>
</div>
</div>
<?php
}
?>
答案 0 :(得分:1)
要解决您的问题,您应该添加一个表单来包装您的输入。
此表单将调用页面本身。在这种形式中,有一个带有文章ID值的隐藏输入。因此,当您提交表单时,您可以通过$ _POST [&#39;隐藏输入的名称&#39;]获取文章ID。
我会告诉你代码:
<?php }
if (isset($_POST['article-id'])) {
// prevent SQL injection
$articleId = mysql_real_escape_string($_POST['article-id']);
$res = mysql_query('DELETE FROM articles_tab WHERE id='.$articleId);
if (!$res) {
die(mysql_error());
}
}
$articles->ArticlesConn();
$result = mysql_query("SELECT * FROM articles_table");
while($row = mysql_fetch_array($result)){ // loop to generate content
?>
<div class="container"> // responsive stuff
<div class="row"> // responsive stuff
<div class="twelve columns"> // responsive stuff
<?php
echo "<h3>" . $row['Title'] . "</h3>
<p>" . $row['Content'] . "</p>"; ?>
</div>
</div>
<div class="row">
<div class="eight columns">
<address><?php echo "Author - " . $row['Author']; ?> </address><br><br><br> /// nick of the author below each article
</div>
<div class="four columns">
<?php
if ($row['Author'] == $_SESSION["username"]) // show delete button if the logged user is an author of generated article
{ ?>
<form method="post">
<input type="hidden" name="article-id" value="<?php echo $row['ID'] ?>"/>
<input type="submit" value="Delete article"/>
</form>
<?php } ?>
</div>
</div>
</div>
<?php
}
但你应该使用mysqli或PDO而不是旧的mysql扩展,看看这个:http://php.net/manual/en/function.mysql-query.php