I have two tables:
Category
| id | name | case |
Items
| id | name | categoryid | <-- this is the relation column
I'm tryig to show all categorys with your respective number of items, like this:
Category Name: Abstract [15 items]
I'm using this code:
$getcategory = mysqli_query($con, "
SELECT c.name
, c.id
, c.case
, i.id
, COUNT(i.categoriaid) AS photos
FROM category c
JOIN items i
ON c.id = i.categoriaid
WHERE i.id != ''
ORDER
BY c.id ASC
");
while ($showcategory = mysqli_fetch_array($getcategory)) {
echo '
<div class="category-container">
<div class="category-title">'.$showcategory['name'].'</div>
<div class="category-img-container">
<div class="img-stretch"><img src="'.$showcategory['case'].'" alt=""/></div>
</div>
<div class="category-count"><div><span class="destaque alto">[ '.$showcategory['photos'].' ]</span> telas</div></div>
</div>
';
}
But this don't work. What's wrong?
The query doesn't look right. There's an aggregate in the SELECT list, and no GROUP BY clause. If the query returns a result, it's going to be a single row. And it doesn't make sense to return non-aggregates in the SELECT list, if we're just going to return a COUNT.
Assuming that id is the PRIMARY KEY (or a UNIQUE KEY) in the category table, if sql_mode doesn't include ONLY_FULL_GROUP_BY, we might be able to get this to run:
SELECT c.name
, c.id
, c.case
, MIN(i.id) AS min_id
, MAX(i.id) AS max_id
, COUNT(i.categoriaid) AS photos
FROM category c
LEFT
JOIN items i
ON i.categoriaid = c.id
AND i.id <> ''
GROUP BY c.id
ORDER BY c.id
If sql_mode includes ONLY_FULL_GROUP_BY, we can either use aggregate functions (e.g. MIN or MAX) around c.name and c.case, or we can extend the GROUP BY clause to include those columns.
SELECT c.name
, c.id
, c.case
, MIN(i.id) AS min_id
, MAX(i.id) AS max_id
, COUNT(i.categoriaid) AS photos
FROM category c
LEFT
JOIN items i
ON i.categoriaid = c.id
AND i.id <> ''
GROUP
BY c.id
, c.name
, c.case
ORDER
BY c.id
Without a specification, we're just guessing. There could any number of things "wrong" with this statement. As a example list: invalid table references, invalid column references (is there a column name categoriaid in the items table? I took that from the SQL in the question).
I suggest you take the SQL writing to another environment and get the SQL written and tested. Then bring that statement back into your PHP code. (Divide and conquer.)
Also, in the PHP code, we can test whether query execution was successful, by testing the return from mysqli_query. If it's FALSE, then we know it wasn't successful, and we can retrieve the error with mysqli_error function.
$sql = "SELECT ... ";
if( !$getcategory = mysqli_query($con,$sql) ) {
// statement execution was not successful
die mysqli_error($con);
}