Displaying all items from mysql database - php

I have table product and table category in my database. I want to display all category dynamically in a table and inside the table of each category I am displaying all item belonged to that category too.
Those categories and items should be displayed like this :
And here is my coding to do the work :
$fetch_cat = "SELECT * FROM tblcat"; //fetch from table category
$result = $conn->query($fetch_cat);
if ($result->num_rows > 0)
{
while($cat_row = mysqli_fetch_assoc($result))
{
$cat_title = $cat_row['catName'];
echo '<table>';
echo '<tr>';
echo '<td><img src="category/'.$cat_row['catImg'].'" /></td>';
echo '<td>';
echo '<ul class="content_init">';
$stmt = "SELECT * FROM tblproduct WHERE prodCat = '".addslashes($cat_title)."' LIMIT 4"; //fetch from table product
$result = $conn->query($stmt);
if ($result->num_rows > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo '<li>';
echo '<a href="#"><img style="height: 188px; width: 188px;" src="user_images/'.$row['prodImg'].'" />';
echo '<br /><br />';
echo '<h4>'.$row['prodName'].'</h4>';
echo '<label><span>RM </span>'.$row['prodPrice'].'</label></a>';
echo '</li>';
}
}
echo '</ul>';
echo '</td>';
echo '</tr>';
echo '</table>';
}
}
Problem :
So the problem with my coding is, it can only display Category 1 with items belonged to it. The rest categories unable to be displayed. I guess my coding might not loop properly because of bad programming as it unable to display the expected output.

The $result variable was reused by the inner query thus the first result override.
Change the variable name either of the $result variable.

$result1 = $conn->query($stmt);
if ($result1->num_rows > 0)
{
while($row = mysqli_fetch_assoc($result1))
{
Your approach is not good/optimal. You have query for the categories and then one query per each category,so if you have 10 categories your code would execute 11 queries. You should do it with one query only using INNER JOIN

You can select all the values left joining the category table for the names and group them by their category ID.
See Group array by subarray values
Afterwards, you can traverse each product for each category by accessing the subarrays.

Related

Rows Sorting properly but not items in those rows?

$sql = "SELECT counter, title FROM items WHERE ORDER BY counter DESC LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$count = $row['counter'];
$i++;
if($i==1){
echo '<div class="row">';
}
echo '<div class="col-sm-3">';
echo '<p><a href="index.php>'.$row[$title].'<br />'.$count.'</a></p>';
echo '</div>';
if($i==4){
echo '</div>';
$i=0;
}
}
}
The code above displays 3 items per row using bootstrap.
The problem I am have is that the ROWS are sorting properly, BUT the 3 items in each row are NOT sorting properly,(by counter DESC).
As an example, I am getting:
<p>1500 -- 1345 -- 1675</p>
<p>1233 -- 1267 -- 1331</p>
<p>1232 -- 1209 -- 1222</p>
As you can see, ALL the items in row 1 are DESC when compared to rows 2 and 3, but the individual items in row one are not sorting properly.
Any thoughts?
Try Using below code
<?php
$sql = "SELECT counter, title FROM items WHERE ORDER BY counter DESC LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$i++;
if($i==1){
echo '<div class="row">';
}
echo '<div class="col-sm-3">';
echo '<p><a href="index.php>'.$row['title'].'<br />'.$row['counter'].'</p>';
echo '</div>';
if($i==4){
echo '</div>';
$i=0;
}
}
}
The PROBLEM was actually in the CSS - the "class="col-sm-3" was set to float-right, therefore reversing the flow of the output. Sorry for the confusion, as the CSS was not present.
This is very interesting that the style dictated the output flow - hmmm.
Thank you for your help Naishant.

Show result of MYSQL select query in two div according to column name, using a single select query

I have a table with column names id, name, category, title,and news. Once select query executes I get all the required data from table but i need to split up this data into two div according to the category they belong. there are two different categories, say A and B.
I need to show all the data with a column category name A in one div and same with category B.
$sql= "SELECT id, title ,news ,category FROM news ";
$query=mysql_query($sql, $ex)or die(mysql_error()) ;
while($row=mysql_fetch_assoc($query)){
$title=$row['title'];
if($row['category']==' Latest News'){
echo $row['title'];
}
}
My code doesn't work. Any idea?
You can first separate out category wise data into separate arrays.
$cat1 = array();
$cat2 = array();
$sql= "SELECT id, title, news, category FROM news";
$query = mysql_query($sql, $ex) or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
if($row['category'] == 'A')
{
$cat['title'] = $row['title'];
$cat['news'] = $row['news'];
$cat1[] = $cat;
}
else
{
$cat['title'] = $row['title'];
$cat['news'] = $row['news'];
$cat2[] = $cat;
}
}
}
Then you can use foreach to print the data into separate div
if(count($cat1) > 0)
{
foreach($cat1 as $category1_data)
{
echo "<div class='cat1'>";
// data of category A
echo "</div>";
}
}
if(count($cat2) > 0)
{
foreach($cat2 as $category2_data)
{
echo "<div class='cat2'>";
// data of category B
echo "</div>";
}
}

using for loop on mysql table

I have 2 tables on my db:
cat (id, catname)
link (id, name, url, cat)
I wanted to loop through the table link and output data by cat, here the actual code but id doesn't work anyway :)
for ($i = 1; ; $i++)
{
$list = $mysqli->query('SELECT * FROM links WHERE category='$i'');
while($row = $list->fetch_assoc()) {
print $row["category"];
print $row["name"].' ';
print $row["url"];
print '<br>';
}
}
$list->free();
Is there a way we can get the id from table cat and use that to loop through the data in table link?
Thanks
No need for so many requests inside the loop. There are JOIN statements in SQL for such cases:
$result = $mysqli->query('SELECT category.name AS cat_name,
links.name,
links.url
FROM category
INNER JOIN links ON links.cat=category.id');
while($row = $result->fetch_assoc()) {
print $row["cat_name"];
print $row["name"].' ';
print $row["url"];
print '<br>';
}
$result->close();

While inside While from different MySQL table

i have 2 tables:
Cat
id,cat_name
SubCat
id, subcat_name, under_cat
i want to make a list that loads the sub category into the correct Category
the problem is with the second loop, i cant make it work
what am i doing wrong?
<?
$query = "SELECT * FROM `Cat`";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()){
echo '<li><a href="#">'
. $row['cat_name'] .
'</a><ul>';
$query2 = "SELECT * FROM `SubCat` WHERE under_cat = '". $row['cat_id'] ."'";
$result2 = $mysqli->query($query2);
while ($row2 = $result->fetch_assoc()){
echo '<li><a href="#">'
. $row2['subcat_name'] .
'</a></li>';
}
echo '</ul></li>';
}
?>
EDIT:
two lists from same category
this is the code:
<?
$query = "SELECT * FROM Cat LEFT OUTER JOIN SubCat ON SubCat.under_cat = Cat.cat_id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()){
echo '<li><a href="#">'
. $row['cat_name'] .
'</a><ul>';
if($row['cat_id'] === $row['under_cat']){
echo '<li>'.$row['subcat_name'].'</li>';
}
echo '</ul></li>';
}
?>
I hate doing SELECT * because of their maintenance problems, but to work with what you did, just do a JOIN:
"SELECT * FROM Cat LEFT OUTER JOIN SubCat ON SubCat.under_cat = Cat.cat_id;"
This will return the result set you want, but you will need to modify your PHP in response to create the list appropriately, something like this:
if($row['cat_id'] === $id){
echo '<li>'.$row2['subcat_name'].'</li>';
} else {
echo '</ul></li><li>'.$row['cat_name'].'<ul>';
iF(!empty($row['subcat_name'])){
echo '<li>'.$row['subcat_name'].'</li>';
}
}
$id = $row['cat_id'];
This will add the items to the list if it is the same as the previous entry, else it will start a new list. The !empty thing is a quick attempt at handling NULLs, as in where there were no matches brought back from SubCat but you had entries in Cat. If this would never be the case, you can eliminate the if statement and convert your query to this:
"SELECT * FROM Cat INNER JOIN SubCat ON SubCat.under_cat = Cat.cat_id;"
Why go through all this effort you ask? Because this will provide the result set you want while only querying once. The way you had it structured prior would query a bazillion times, which kills the server and greatly reduces performance.
Hopefully this helps both your problem and you're overall implementation knowledge.

Same query, different results in php vs phpmyadmin- Why?

I am trying to get the total actions from each employee in a MySQL database. My script is giving me a significantly lower total than the number in the database for all employees. I am using a SUM function in the query. The query works fine in phpmyadmin, but not in my script. Any ideas why this is happening.
$query = "SELECT user_id, SUM(num_actions) as action FROM pro_actions GROUP BY user_id ORDER BY action DESC";
if ($result = $db->query($query)) {
$count = 0; // this is the total of all employee actions. which adds up correctly!
while ($row = mysqli_fetch_array($result)) {
$count += $row['action'];
echo '<tr><td>';
echo $row['user_id'];
echo '</td><td>';
echo $row['action'];
echo '</td></tr>';
}
$result->free();
}
When I run this script, employee 1005 has 63 actions. However, when I run this query in phpmyadmin, employee 1005 has 194 actions (which is correct). All employees have fewer actions in the output of the script. The interesting thing is that the $count variable outputs the correct amount, which is the total of all actions... Please help with this glitch.
$query = "SELECT user_id, SUM(num_actions) as action FROM pro_actions GROUP BY user_id ORDER BY action DESC";
if ($result = $db->query($query)) {
$count = 0; // this is the total of all employee actions. which adds up correctly!
while ($row = mysqli_fetch_array($result)) {
$count += $row['action'];
echo '<tr><td>';
echo $row['user_id'];
echo '</td><td>';
echo $row['action'];
echo '</td></tr>'; //tag mismatch
}
$result->free();
}

Categories