Reputation: 1557
I am using the count(*) AS, as an alternative to mysql_num_rows(). I get a count for all 3 kinds of feedback (positive, negative and neutral).
But I don't know how to assign the count of, say, positive feedback to a variable that I would call $positive_feedback
and then, echo it. How can you do this with the following example?
I have this:
SELECT feedback, count(*) AS `count`
FROM feedback
WHERE seller='$user'
GROUP BY feedback
which gives something like that:
feedback | count
----------------
positive | 12
neutral | 8
negative | 3
Upvotes: 0
Views: 299
Reputation: 11270
With PDO it will look something like this:
$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);
Upvotes: 1
Reputation: 19985
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);
Upvotes: 2
Reputation: 2246
$result = mysql_query($query); // with your query.
$feedback=array();
while ($row = mysql_fetch_assoc($result)) {
$feedback[$row['feedback']]=$row['count'];
}
It will give an array consisting of feedback['positive'],feedback['negative'] and so on with count stored in each.
Upvotes: 4