using for loop on mysql table - php

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();

Related

Loop through one table with another loop for each record

I have one table with categories and another table with linkrecords for each category and the table structure looks like this:
categories:
id (int)
name (varchar)
links:
id (int)
link (varchar)
fk_cat_id (int)
Here is how I do now, but know that it is a no go with a query within a query:
$query = "SELECT * FROM categories";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$catid = $row['cat_id'];
echo 'CatName: '.$row['name'];
echo '<ul>';
$query2 = "SELECT * FROM links WHERE fk_cat_id = $catid";
if ($result2 = $mysqli->query($query2)) {
while ($row2 = $result2->fetch_assoc()) {
echo '<li>'.$row2['link'].'</li>';
}
}
echo '</ul>';
}
}
I guess I have to go to some JOIN method, but not sure how!
Following query will be used to retrieve links with relation to link categories.
Also, It is a good practice to specify fields name in query to retrieve specific columns only instead of *.
SELECT links.id AS link_id, links.link, links.fk_cat_id, categories.name
FROM links
JOIN categories ON categories.id = links.fk_cat_id;

Displaying all items from mysql database

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.

News comments count

I'm tired of searching for the solution my news comment system.
What i have.
I have 2 different mysql tables item (id, title, category_id, details) and comments (id, item_id, comment)
If i have single news then counting is fine like here in picture:
Single news
Code:
if (!empty($comments)) {
$comm = count($comments);
} else {
$comm = 0;
}
But if i use same code category view, result is:
Category view
If i use code:
$sqls = mysql_query("SELECT c.item_id,
COUNT(c.comment)
FROM comments c
RIGHT JOIN items i
ON c.item_id = i.id
GROUP BY c.item_id");
$comm = mysql_num_rows($sqls);
$smarty->assign('comm',$comm);
Result is :Some number of comments
How to make possible to see the Category View the correct number of comments?
TRY this example. The result is the same as the screenshot below but with some background colour to distinguish the difference. Of course you should change to your own connection and layout.
<?php
$db = new PDO('sqlite:news.db');//change to your own
$sql = $db->prepare("
SELECT item.id, item.title, item.details, comments.comment, COUNT(comments.id) AS NumberOfComment
FROM item LEFT JOIN comments ON item.id = comments.item_id
GROUP BY item.id ORDER BY item.id");
$sql->execute();
$row = $sql->fetchAll();
//get comment
$comment = $db->prepare("SELECT comment FROM comments WHERE item_id = ?");
foreach ($row as $rows){
echo "<br>";
echo "Title: ".$rows['title'];
echo "<br>";
echo "Details: ".$rows['details'];
echo "<br>";
echo "<i>".$rows['NumberOfComment']." comments </i>";
echo "<br>";
$comment->execute(array($rows['id']));
$comments = $comment->fetchAll();
echo '<div style="background-color:pink;">';
foreach ($comments as $showcomment){
echo $showcomment['comment'];
echo "<br>";
}
echo "</div>";
echo "<br>";
}
?>
example item table
example comment table
and the result is...

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>";
}
}

Display more than one row from SQL SELECT

I want to display all of the rows shown in the picture where CID = 1.
Here is my PHP code with SQL:
`
$contractCount = 1;
$sql = "SELECT categories.categoryID
FROM categories
LEFT JOIN link
ON categories.categoryID = link.categoryID
WHERE link.CID = '$contractCount'";
$res = $con->query($sql);
if (!$res) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_array($res)) {
echo $row['categoryID'];
}
Here is an image showing the table in PHPMyAdmin called categories.
So I need output as ITSM, Mar and HrAd but I am only getting ITSM and not the rest.
EDIT 1: The LEFT JOIN makes no difference here, the link table has no bearing on the SELECT statement
EDIT 2: I have solved the problem, my mistake was that I had the table names the wrong way round in the SQL query.
You need to use the function mysql_fetch_row, this will fetch a row and move the pointer to the next one.
while ($row = mysqli_fetch_row($res)) {
echo $row['categoryID'];
}

Categories