Msqli, how group "graphically" a query from 2 different tables - php

I have 2 tables:
table 1) courses_cat (this one have a "title" field)
table 2) courses (this one have a "parent" field which I want use to "group", this "parent" is equal to "title"
So I need to put "graphically" the content of the table 2 inside the table 1.
Here my code (separated for both tables):
<?php
$query = $db->prepare('SELECT title, body, showeb, datapost FROM courses_cat WHERE showeb="si"');
$query->execute();
$query->store_result();
$query->bind_result($title, $body, $showeb, $datapost);
while ($query->fetch())
echo " <div class='pblock'><h2>$title</h2><pre>$body</pre></div> ";
?>
<?php
$query2 = $db->prepare('SELECT parent, title, body, showeb, datapost FROM courses WHERE showeb="si"');
$query2->execute();
$query2->store_result();
$query2->bind_result($parent, $title, $body, $showeb, $datapost);
while ($query2->fetch())
echo " <div id='courseblock'><a href='#'><span class='top'>$title</span><span class='content'>$shortbody</span></a></div>";
?>

I'm not sure I understand 100% what the end result should be, but I'm sure you can merge your two queries into one; looping over this properly might solve your issue:
SELECT cat.title as CatTitle, cat.body as CatBody, courses.title as CourseTitle, courses.body as CourseBody -- and any other fields you need like that
FROM courses_cat cat, courses
WHERE cat.parent = courses.title
GROUP BY cat.title

I try the code posted by Digital Chris, and it works (in part), for explain better, the follow code (see below the edited one) "group ok the categories and put the items inside" but I need to get more of one Course (div "courseblock") into each Category (div "pblock") and this code print just oneā€¦(I think it "break the loop" and maybe need to JOIN the data of the "courses" into their "categories")
At this link can see an graphic example of what I mean:
http://liberartestudio.com/download/aaa.jpg
(the category blocks are those whites, the courses those red)
Here the link to the page:
http://lvdsys.liberartestudio.com/services_courses.php
<?php
$query = $db->prepare('
SELECT courses_cat.title AS CatTitle, courses_cat.body AS CatBody, courses_cat.datapost AS CatData, courses.parent, courses.title AS CourseTitle, courses.shortbody AS CourseShortbody, courses.datapost AS CourseData
FROM courses_cat, courses
WHERE courses_cat.title = courses.parent
GROUP BY parent
ORDER BY CatData AND CourseData
');
$query->execute();
$query->store_result();
$query->bind_result($CatTitle, $CatBody, $CatData, $parent, $CourseTitle, $CourseShortbody, $CourseData);
while ($query->fetch())
echo "
<div class='pblock'>
<h2>$CatTitle</h2><pre>$CatBody</pre>
<div id='courseblock'><a href='#'><span class='top'>$CourseTitle</span><span class='content'>$CourseShortbody</span></a>
</div>
</div>
"; ?>

Here my working code (simple version) for what I needed...
<?php
$cat = mysqli_query($db,"SELECT title AS catTitle, body AS catBody FROM courses_cat");
$result = mysqli_query($db,"SELECT parent, title, shortbody FROM courses");
//array x categories
$category = array(); while ($row = mysqli_fetch_assoc($cat)) {$category[] = $row;}
//array x courses
$course = array(); while ($row = mysqli_fetch_assoc($result)) {$course[] = $row;}
// here my divs
$cat_div="";
foreach ($category as $row) {
$cat_div = $row['catTitle'];
echo "<div class='pblock'>";
echo "<h2>".$row['catTitle']."</h2><pre>".$row['catBody']."</pre>";
foreach ($course as $row) {
if ($cat_div == $row['parent']) {
echo "<div id='courseblock'><a href='#'><span class='top'>".$row['title']."</span><span> class='content'>".$row['shortbody']."</span></a></div>";}}
echo "</div>";}
$cat->free_result();
$result->free_result();
mysqli_close($db);
?>

Related

How to prevent title repeating in php mysqli

I have joined two table images and post tables my script problem when i uploaded two or more images to image table post table title only one but it repeating images like number i want to know how to fix it anyone can help me thanks my English problem
Post table like this
id title
3 example
Images table like this
id img post_id
1 123.jpg 3
2 22.jpg 3
3 11.jpg 3
4 21.jpg 3
5 34.jpg 3
Post title one but it repeating 5 time images with i want to prevent it
Here is my source code
<?php
if ($stmt = $con->prepare(" SELECT p.*,i.img,title,id
from post AS p LEFT JOIN images AS i ON i.post_id= p.id ")) {
$stmt->execute();
}
$result = $stmt->get_result();
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
?>
<?php echo $row['title']; ?>
<img src="images/<?php echo $row['img']; ?>"height="20"width="20"/>
<?php
}}
?>
<?php
if ($stmt = $con->prepare(" SELECT p.*,i.img,title,id
from post AS p LEFT JOIN images AS i ON i.post_id= p.id ")) {
$stmt->execute();
}
$result = $stmt->get_result();
if ($result->num_rows>0) {
$firstTime=true;
while ($row = $result->fetch_assoc()) {
?>
<?php
if($firstTime==true){
echo $row['title'];
$firstTime=false;
}
?>
<img src="images/<?php echo $row['img']; ?>"height="20"width="20"/>
<?php
}}
?>
The column title will be repeated equal to the number of rows returned in the image table, you can not do anything to prevent it.
If you do group by title it will return the number of rows equal to the number of rows in the post table.
But if you elaborate more on what you actually want to do with the result I may help you.
Try this please :-
<?php
$a1 = "";
$stmt = $con->prepare("SELECT p.*,i.img,title,id
from post AS p INNER JOIN images AS i ON i.post_id=p.id");
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
$title = $row['title'];
$img = $row['img'];
}
if($a1!= $title){
$activity="";
$activity.="<tr>
<td>$title</td>
</tr>;
}
$activity.="<tr>
<td><img src="images/<?php echo $img ?>"height="20"width="20"/></td>
</tr>";
$a1=$title;
}
?>

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;

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...

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

PHP & MYSQL: using group by for categories

My database has the following setup
productid | productname | category id
and I want to output them like so:
category #1
item 1
item 2
item 3
category #2
item 1
item 2
item 3
I used group by the group them together and that works fine, but I want to loop through each group and display the contents of that group. How would I do this?
I'd recommend just a simple query to fetch all the rows, sorted by category id. Output the category only if its value changes from the previous row.
<?php
$stmt = $pdo-> query("SELECT * FROM `myTable` ORDER BY categoryID");
$current_cat = null;
while ($row = $stmt->fetch()) {
if ($row["categoryID"] != $current_cat) {
$current_cat = $row["categoryID"];
echo "Category #{$current_cat}\n";
}
echo $row["productName"] . "\n";
}
?>
This should work:
$categories = array();
$result= mysql_query("SELECT category_id, product_name FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
while($row = mysql_fetch_assoc($result)){
$categories[$row['category_id']][] = $row['product_name'];
}
// any type of outout you like
foreach($categories as $key => $category){
echo $key.'<br/>';
foreach($category as $item){
echo $item.'<br/>';
}
}
The output you can style yourself. You simply add everything into a multidimensional array with the category id as the first level keys.
EDIT: The resulting array might look like this:
$categories = array(
'cateogy_id_1' => array(
1 => 'item_1',
2 => 'item_2',
...
),
'cateogy_id_2' => array(
1 => 'item_1',
2 => 'item_2',
...
),
....
);
What you want is to order them by the category, not group them.
SELECT * FROM MyTable
ORDER BY category_id, product_id
When you iterate through the list, just output a new header whenever the category_id changes.
This approach does not need the data to be sorted by category_id.
You can use php to group each category together in a nested array.
After this, the data can be easily be displayed in a table, passed to a grap/chart library, etc...
<?php
$stmt = $pdo-> query("SELECT * FROM myTable ORDER BY categoryID");
$categories = []; //the array to hold the restructured data
//here we group the rows from different categories together
while ($row = $stmt->fetch())
{
//i'm sure most of you will see that these two lines can be performed in one step
$cat = $row["categoryID"]; //category id of current row
$categories[$cat][] = $row; //push row into correct array
}
//and here we output the result
foreach($categories as $current_cat => $catgory_rows)
{
echo "Category #{$current_cat}\n";
foreach($catgory_rows as $row)
{
echo $row["productName"] . "\n";
}
}
?>
The easiest way is probably to pull the list of categories, iterate through and pull their attached products. (I.e. several queries.)
For instance (pseudocode):
$result = fetch_assoc("SELECT category_id FROM categories");
foreach($result as $row)
{
echo $row['category_id'];
$result2 = fetch_assoc("SELECT product_id FROM products");
foreach($result2 as $row2)
{
echo $row2['product_id'];
}
}
If you want to do it all in one query you can do something like:
$result = fetch_assoc("SELECT product_id, category_id FROM products p JOIN categories c ON p.category_id = c.category_id ORDER BY c.category_id ASC");
$last = null;
foreach($result as $row)
{
# Output the category whenever it changes
if($row['category_id'] != last)
{
echo $row['category_id'];
$last = $row['category_id'];
}
echo $row['item_id'];
}
Then you can iterate over the result set and pull out the category name whenever it changes.
There may be a more sophisticated, elegant way to write the SQL to do everything before you get it from the database, but I'm not that smart. ;)
Note: Examples use pseudo code. I use a mysql abstraction class that works like:
$db->query("SELECT stuff");
$db->multi_result(); // returns 2d-associative array
I can then foreach($db->multi_result() as $row), which is super lazy and awesome.
I can post the code for the abstraction layer if you like.
$stmt = $dbConnection->prepare("SELECT exam_id, COUNT(report_id) FROM bug_report GROUP BY exam_id; ");
//$stmt->bind_param('s',$exam_id);
$stmt->execute();
$extract = $stmt->get_result();
$count = $extract->num_rows;
if($count){
while($rows = $extract->fetch_assoc()){
$exam_id = $rows["exam_id"];
switch($exam_id){
case "jee_questions":
$jeeBugCount = $rows["COUNT(report_id)"];
break;
case "gate_questions":
$gateBugCount = $rows["COUNT(report_id)"];
break;
}
}
}

Categories