Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP/MySQL Join statement not working
    primarykey
    data
    text
    <p>I am trying create an average rating for a store listing using Mysql <code>AVG</code> and then displaying the average next to each store on a directory list page. </p> <p>Every time someone leaves a review for a store, they give a rating of 1-5, which is inserted into <code>TABLE reviews</code> in column <code>rating</code></p> <p>The store data is coming from <code>TABLE reviews</code> and the table relationship is coming from a column in both tables named <code>store_id</code>. I trying to use a join statement to get the average to display next to each store.</p> <p>This is the current code in the loop for the rating with join statement:</p> <pre><code>&lt;?php echo "&lt;table&gt;\n"; echo "&lt;tr&gt;&lt;th&gt;Store ID&lt;/th&gt;&lt;th&gt;Rating&lt;/th&gt;&lt;/tr&gt;\n"; $result1 = mysql_query("SELECT s.store_id AVG(r.rating) AS avg_rating FROM stores as s JOIN reviews as r ON s.store_id = r.store_name GROUP BY s.store_id"); while ($row1 = mysql_fetch_assoc($result1)) { echo "&lt;tr&gt;&lt;td&gt;$row1[store_id]&lt;/td&gt;&lt;td&gt;$row1[avg_rating]&lt;/td&gt;&lt;/tr&gt;\n"; } echo "&lt;/table&gt;\n";?&gt; echo "&lt;/table&gt;\n";?&gt; </code></pre> <p>This is the SQL error I am getting</p> <pre><code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(r.rating) AS avg_rating FROM stores' </code></pre> <p>This is the PHP error I am getting:</p> <blockquote> <p>Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/shopping/public_html/retailers.php on line 227</p> </blockquote> <p>Line 227 is this line from the code above:</p> <pre><code>while ($row1 = mysql_fetch_assoc($result1)) { </code></pre> <p>These are my tables 2 structures:</p> <pre><code>CREATE TABLE `stores` ( `store_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `store_name` varchar(255) NOT NULL DEFAULT '', CREATE TABLE `reviews` ( `rating_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL DEFAULT '0', `rating` tinyint(1) NOT NULL DEFAULT '0', </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload