更新数据库中的注释数

更新数据库中的注释数

问题描述:

I'm trying to update the comments column in one table (Entries), when a new row is added to another table (blog_comments). This code is inside of the PHP function that adds a comment to the DB:

    $count = mysql_query("SELECT COUNT(*) FROM blog_comments WHERE entry_title='$entry_title'");
$update = mysql_query("UPDATE Entries SET comments='$count' WHERE title='$entry_title'");

$entry_title is the name of the page. This code does nothing as of now; it doesn't change anything. I'm not sure what I'm doing wrong. Any ideas?

我正在尝试更新一个表(条目)中的注释列,当一个新行添加到另一个表中时 表(blog_comments)。 此代码位于向DB添加注释的PHP函数内: p>

  $ count = mysql_query(“SELECT COUNT(*)FROM blog_comments WHERE entry_title ='$ entry_title'  “); 
 $ update = mysql_query(”UPDATE Entries SET comments ='$ count'WHER title ='$ entry_title'“); 
  code>  pre> 
 
 

$ entry_title is 页面的名称。 此代码现在没有任何作用; 它没有改变任何东西。 我不确定我做错了什么。 有什么想法吗? p> div>

mysql_query() doesn't return the result directly. It returns a resource which you can use to get the result:

$result = mysql_query("SELECT COUNT(*) FROM blog_comments WHERE entry_title='$entry_title'");
$row = mysql_fetch_array($result);
$count = $row[0];
$update = mysql_query("UPDATE Entries SET comments='$count' WHERE title='$entry_title'");

Two things worth mentioning:

  1. Using a title as a foreign ke isn't generally advisable. You should be using a blog post ID or something (imho); and

  2. This represents a denormalization, which can be useful if you have a performance issue. Otherwise it can create problems if the numbers somehow get out of sync. You can write one query that in one round trip pulls back the blog posts and the number of comments (as a subquery).