简体   繁体   English

如何检查记录是否删除是最后一条记录是否遗留MySQL PHP

[英]How to check if record deleted was last record left MySQL PHP

So I have a comments section on my website (blog style), so every post has a comments section. 因此,我在我的网站上有一个评论版块(博客样式),因此每个帖子都有一个评论版块。

I have a table 'posts' fields (post_id, isComment, title, timestamp, post etc.) 我有一个表格“ posts”字段(post_id,isComment,title,timestamp,post等)

isComment is a boolean value which refers to if the post has any comments. isComment是一个布尔值,表示帖子中是否有任何评论。 If 0, no comments are searched for or shown, if 1, querys the table comments for comments for that post. 如果为0,则不搜索或不显示任何注释;如果为1,则在表注释中查询该帖子的注释。

There's also a table 'comments' which has fields (comment_id, post_id, created etc..) 还有一个表“ comments”,其中包含字段(comment_id,post_id,已创建等)。

The post_id is the post the comment corresponds to. post_id是评论对应的帖子。

Currently the query to remove a comment is: 当前,删除评论的查询是:

 "REMOVE FROM comments WHERE comment_id = '$id';"

What I want to know, is if there is any way to find out if the comment deleted was the last comment corresponding to that post? 我想知道的是,是否有办法找出删除的评论是否是与该帖子相对应的最后一条评论? And if so, then I would change the isComment value of that post to 0. 如果是这样,则可以将该帖子的isComment值更改为0。

You can fire a query to find number of comments for that post, after every delete of a comment. 每次删除评论后,您都可以触发查询以查找该帖子的评论数。

Something like. 就像是。

select count(*) from comments where post_id = (select post_id from comments where comment_id='$id')

// You can optimize the query if u want. //您可以根据需要优化查询。

Query for any comments of the given posts. 查询给定帖子的任何评论。 If no rows are returned, reset your isComment flag with another query. 如果未返回任何行,请使用另一个查询重置isComment标志。 (There might be a more efficient way to use the database to use its functions to calculate the number of rows and act accordingly.) (使用数据库来使用数据库的功能来计算行数并采取相应措施可能是一种更有效的方法。)

There are a couple ways to go about this. 有几种方法可以解决此问题。 First, you could just count how many are left and act accordingly: 首先,您可以算出剩下的数量并采取相应措施:

SELECT count(*) FROM comments WHERE post_id = '$id'

Or, if you already have the comment count when removing the comment, you can call mysql_affected_rows(...) or mysqli_affected_rows(...) to determine if something actually was deleted and how many. 或者,如果删除注释时已经具有注释计数,则可以调用mysql_affected_rows(...)mysqli_affected_rows(...)来确定是否实际删除了多少个对象。

Also, I believe in your original query, I believe your syntax should be DELETE instead of REMOVE? 另外,我相信您的原始查询,我相信您的语法应为DELETE而不是REMOVE?

DELETE FROM comments WHERE comment_id = '$id';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM