2010-01-14 148 views
0

我想要计算某个文章已被评分的次数,例如我的成员已经对users_articles_id3进行了评分。PHP和MySQL问题

我也想算一定的文章例如users_articles_id3由其ratings_id的等级分关系到ratings数据库中的点应该是一个总的13

我不知道如果我是这样做是正确的,因为对我来说它看起来都错了?我希望如果有人能帮我解决这个问题?我的代码应该放在哪里?

我正在使用PHP和MySQL?

这里是我的MySQL表

CREATE TABLE articles_grades (
id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
ratings_id INT UNSIGNED NOT NULL, 
users_articles_id INT UNSIGNED NOT NULL, 
user_id INT UNSIGNED NOT NULL, 
date_created DATETIME NOT NULL, 
PRIMARY KEY (id) 
); 


CREATE TABLE ratings (
id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
points FLOAT UNSIGNED NOT NULL DEFAULT 0, 
PRIMARY KEY (id) 
); 



数据库输入

articles_ratings

id ratings_id users_articles_id user_id  date_created 
1 3   2     32   2010-01-13 02:22:51 
2 1   3     3   2010-01-13 02:23:58 
3 2   3     45   2010-01-13 02:24:45 

评级

id  points 
1  10 
2  3 
3  5 



这里是我试图解决的PHP代码。

// function to retrieve rating 
function getRating(){ 
    $sql1 = "SELECT COUNT(*) 
         FROM articles_ratings 
         WHERE users_articles_id = '$page'"; 

    $result = mysql_query($sql1); 
    $total_ratings = mysql_fetch_array($result); 

    $sql2 = "SELECT COUNT(*) 
          FROM ratings 
          JOIN ratings ON ratings.id = articles_ratings.ratings_id 
          WHERE articles_ratings.users_articles_id = '$page'"; 

    $result = mysql_query($sql2); 
    $total_rating_points = mysql_fetch_array($result); 
    if(!empty($total_rating_points) && !empty($total_ratings)){ 
    // set the width of star for the star rating 
    $rating = (round($total_rating_points/$total_ratings,1)) * 10; 
    echo $rating; 
    } else { 
     $rating = 100; 
     echo $rating; 
    } 
} 
+1

当你说你试图“修复”这段代码时,你遇到了什么问题? – AaronLS

+0

目前尚不清楚问题是什么,你只是说'修复'。你能否详细说明你在上面的代码中遇到的问题。说这一切看起来错了有点通用。 – Camsoft

回答

1

嗯,我认为这里有几个问题。

1)您正在定义名为articles_grades,而不是articles_ratings的表,如同在您的代码中一样。 2)为什么articles_grades和rating需要在不同的表格中?这些表格之间有一对一的对应关系。 3)您需要在第二个查询中进行求和(点数)。 4)您可以将两个查询组合成一个查询。

这是我会怎么做,如果你不改变模式:

<?php 

mysql_connect('localhost','root','fake123123'); 
mysql_select_db('test'); 

$result = mysql_query('SELECT users_articles_id,count(*),sum(r.points) 
FROM articles_grades ag,ratings r 
WHERE ag.ratings_id = r.id 
GROUP BY users_articles_id'); 

if (!$result) 
    die('invalid'); 
else{ 

    echo '<table><tr><th>Article Id</th><th>#Ratings</th><th>#Points</th></tr>'; 
    $a = mysql_fetch_row($result); 
    while($a){ 
    echo '<tr><td>'.implode('</td><td>',$a).'</td></tr>'; 

    $a = mysql_fetch_row($result); 
    } 
    echo '</table>'; 

} 

?> 

可以作为一个CGI脚本运行此。它应该返回一个结果表。

让我知道这是否有帮助。