0

我正在使用 count(*) AS,作为 mysql_num_rows() 的替代方法。我计算了所有 3 种反馈(正面、负面和中性)。

但是我不知道如何将正反馈的计数分配给我要调用的变量,$positive_feedback然后回显它。你怎么能用下面的例子做到这一点?

我有这个:

SELECT feedback, count(*) AS `count` 
FROM feedback 
WHERE seller='$user' 
GROUP BY feedback

这给出了类似的东西:

feedback | count
----------------
positive |   12
neutral  |   8
negative |   3
4

3 回答 3

4
$result = mysql_query($query);  // with your query.

$feedback=array();
while ($row = mysql_fetch_assoc($result)) {
   $feedback[$row['feedback']]=$row['count'];
}

它将给出一个由 feedback['positive']、feedback['negative'] 等组成的数组,其中每个都存储计数。

于 2012-05-19T18:28:56.223 回答
2

Use Count(1), not Count(*), it's faster because the SQL engine can just use the count values from the counting B-Tree index and does not need to ever access any other values. If you plan to make this query a lot, make sure you add an index on the feedback tuple.

$query = "SELECT feedback, count(1) AS `count`...";
$result = mysql_query($query, $link); // don't forget to share your db conn

$feedbackArr = new array();
while ($row = mysql_fetch_assoc($result)) {
    $feedbackArr[$row['feedback']] = (int)$row['count'];
}

echo "Positive Feedback: \n";
print_r($feedbackArr);
于 2012-05-19T18:39:46.027 回答
1

使用 PDO,它看起来像这样:

$dsn = "mysql:host=%;dbname=%"; // insert your host and dbname

$db = new PDO($dsn, $username, $password); // insert your username and pass

$sql = "
  SELECT 
    feedback, count(*) AS `count` 
  FROM 
    feedback 
  WHERE 
    seller='$user' 
  GROUP BY feedback
";

$feedback = array();
foreach ( $db->query($sql) as $row ) {
  $feedback[ $row['feedback'] ] =  $row['count'];
}

// result in here
print_r ($feedback);
于 2012-05-19T18:35:37.283 回答