total_starsHere is the code, it is the best explanation of what I am trying to do:
$total_stars = array();
$query = "SELECT items_id FROM items";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$item_id = $row['items_id'];
$sql = "Select Count(item_id) FROM ratings WHERE item_id = '{$item_id}'";
$result = mysql_query($sql);
$total_stars[] = mysql_fetch_array($result);
}
// To see the output by entering the URL I want to print_r
print_r($total_stars);
// In the end, I am trying to JSON encode this and will later output in Java for Android
print(json_encode($total_stars));
(So as not to confuse, the items_id is in items table, item_id (without an 's') is in ratings table)
Now in plain English:
I am looping through each row in the items table. As I do that, in each loop I am referring to another table called "Ratings", and getting a count of how many ratings for that item.
For example I want an array to look like (65, 43, 55, 43, etc). Sample numbers of course. But each represent the total amount of ratings for each item in a table. How can I get print__r to display the results of the SQL statement inside the loop?
UPDATED CODE TRYING TO USE JOIN:
$query = "SELECT items_id FROM items";
$q = 'SELECT
items.items_id,
COUNT(ratings.item_id) AS rate
FROM `items`
LEFT JOIN ratings ON (ratings.item_id = items.items_id)
GROUP BY items_id';
$result = mysql_query($q);
while ($row = mysql_fetch_array($result)) {
$total_stars = mysql_fetch_array($result);
}
print_r($total_stars);
print_r outputs this: Array ( [0] => 783 [items_id] => 783 [1] => 0 [rate] => 0 )