Datebase and php parent id - php

Hello i'm working on this all day today and i'm actually really lost i have a table like this at the moment.
id | category | parent_id
id=5 category=Laptop parent_id=0
id=7 category=Houses parent_id=0
id=8 category=HP parent_id=5
id=9 category=Lenovo parent_id=5
so what i'm trying to do is get this as a category sub category style something like;
Laptop
HP
Lenovo
Houses
until know what i have;
<?php
include_once("dir/db.php");
$result = $db->query("SELECT * FROM categories WHERE parent_id = 0");
?>
<ul>
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)):
?>
<li><?php echo $row['category'] ?></li>
<?php endwhile;?>
</ul>
output;
<ul>
<li>Laptops</li>
<li>Houses</li>
</ul>
but i'm trying to get my Lenovo and HP under Laptop i'd be really happy if you can help me! Thanks.

<?php
include_once("dir/db.php");
$result = $db->query("SELECT * FROM categories WHERE parent_id = 0");
echo "<ul>";
while($row = $result->fetch(PDO::FETCH_ASSOC)):
echo "<li>" . $row['category'] . "</li>";
$sub_result = $db->query("SELECT * FROM categories WHERE parent_id = " . $row['id']);
echo "<ul>";
while($sub_row = $sub_result->fetch(PDO::FETCH_ASSOC)):
echo "<li>" . $sub_row['category'] . "</li>";
endwhile;
echo "</ul>";
endwhile;
echo "</ul>";
?>

Related

What can I do with this problem with mysql php and table result?

I have this query to list name categories and avg of each one, but the result is not what I want, how to sove this? if you look to image you see that the table resulta don't show correct
$query = $connMysqli->query("SELECT qc.name as cat_name
FROM fhrw_question_categories qc
...
group by Quiz, cat
ORDER BY u.id");
?>
<table>
<tr>
<?php
while($row = $query->fetch_assoc()){
echo '<th>' . $row['cat_name'] . '</th>';
}?>
</tr>
<!-- table continiuous avg-->
<?
$query = $connMysqli->query("SELECT avg(IFNULL(fraction, 0)) * 10 as Media, u.ud as student, qc.name as cat_name
FROM fhrw_question_attempt_steps qc
...
group by Quiz, u.id, cat
ORDER BY u.id ASC");
?>
<?php
while($row = $query->fetch_assoc()){
echo '<tr><td>' . $row['cat_name'] . ' - ' . round($row['Media'],2) . '</td></tr>';
}?>

display each category with their items from table in select option

I've one table products_tbl
+----------+-----------+---------------+
|product_id|ProductName|ProductCategory|
+----------+-----------+---------------+
|1 |Apple |fruits |
|2 |Orange |fruits |
|3 |Iphone X |Electronics |
|4 |FJ-Eye Lens|Accessories |
+----------+-----------+---------------+
i want to display each categories items in separated group using HTML SELECT OPTION
products.php
$productQ = "SELECT * FROM products_tbl ";
try {
$stmt2 = $db->prepare($productQ);
$stmt2->execute();
} catch(PDOException $ex) {
die("Failed to run Query: " . $ex->getMessage());
}
$produtsrows = $stmt2->fetchAll();
echo"<select>";
foreach($produtsrows as $prow):
echo "<optgroup label=".$prow['ProductCategory'].">";
echo" <option>".$prow['ProductName']."</option>
</optgroup>";
endforeach;
echo "
</select>
";
it display it like so
fruits
Apple
fruits
Orange
Electronics
Iphone X
Accessories
FJ-Eye Lens
You need to change your foreach loop to not output the category name when it is the same as the last one:
$last_cat = "";
foreach($produtsrows as $prow):
if (($cat = $prow['ProductCategory']) != $last_cat) {
if ($last_cat != "") echo "</optgroup>\n";
echo '<optgroup label="'.$cat.'">' . "\n";
$last_cat = $cat;
}
echo" <option>".$prow['ProductName']."</option>\n";
endforeach;
echo "</optgroup>\n";
Output (for your data)
<optgroup label="fruits">
<option>Apple</option>
<option>Orange</option>
</optgroup>
<optgroup label="Electronics">
<option>Iphone X</option>
</optgroup>
<optgroup label="Accessories">
<option>FJ-Eye Lens</option>
</optgroup>
I changed your code a little bit:
$productQ = "SELECT * FROM products_tbl ORDER BY ProductCategory ASC";
try {
$stmt2 = $db->prepare($productQ);
$stmt2->execute();
} catch(PDOException $ex) {
die("Failed to run Query: " . $ex->getMessage());
}
$produtsrows = $stmt2->fetchAll();
echo"<select>";
$category = "";
foreach($produtsrows as $prow):
if ($category != $prow['ProductCategory']) {
if ($category != "") {
echo "</optgroup>";
}
$category = $prow['ProductCategory'];
echo "<optgroup label=".$prow['ProductName'].">";
}
echo" <option>".$prow['ProductName']."</option>
endforeach;
echo "</optgroup>
</select>
";
First note that I added ORDER BY ProductCategory ASC to be sure that all products with same category are always together.
Next I Add the <optgroup> label only when the category is different from the previous item.
Note that I am assuming all products have a valid category. If you have empty categories the resulting html will be messed up.

How to list values in category and subcategory with foreach PHP

My clothes db like:
jeans | Bootcut
jeans | Straight
jeans | Slim
jacket| ..
shoes | ..
I try to list the products like in shops with following code:
<?php
$sql = 'SELECT DISTINCT category FROM clothes ';
$sqlSubcat = 'SELECT subcategory FROM clothes ';
echo '<div>'
foreach ($conn->query($sql) as $row) {
echo ' <a>'.$row['category'].'</a> ';
foreach ($conn->query($sqlSubcat) as $row) {
echo ' <div >';
echo ' <a>'.$row['subcategory'].'</a> ';
echo ' </div>';
}
}
echo "</div>";
?>
my expect:
but I get this result:
Only 1 subcategory will be listed instead of 3. Where is the mistake in the code?
I think shouldn't used execute sql query directly in foreach loop. You try this sample:
$sql = 'SELECT DISTINCT category FROM clothes ';
$sqlSubcat = 'SELECT subcategory FROM clothes ';
$tmp1 = $conn->query($sql);
$tmp2 = $conn->query($sqlSubcat);
echo '<div>';
foreach ( $tmp1 as $row1) {
echo ' <a>'.$row1['category'].'</a> ';
foreach ( $tmp2 as $row2) {
echo ' <div >';
echo ' <a>'.$row2['subcategory'].'</a> ';
echo ' </div>';
}
}
echo "</div>";
?>

menu with submenu using mysql

Hello I just a little but help.
What I am trying to do is create a menu with a submenu by getting the data from 2 different mysql tables.
The issue I am having is the submenu will not display all results from the "Sub Category" database depending on what page I am on
Table 1: Category "ID, Name"
Table 2: Sub Category "ID, Name, Cparent, filename (Image for sub category)"
I have the following code:
<ul>
<?php
$catmenu_sql = 'select category.id AS catid, category.name AS catname, scategory.cparent AS scparent, scategory.name AS scname
from category
left join scategory on category.id = scategory.cparent
group by category.name'; // Select data from database
$result = mysql_query($catmenu_sql);
while($rows = mysql_fetch_array($result)) { ?>
<!-- Begin Category list -->
<li class="menu">
<?php echo($rows['catname']); ?>
</li>
<!-- End Category List -->
<?php
if (isset($_GET['id']) && is_numeric($_GET['id'])) // get the 'id' variable from the URL and match it with scategory parent in database
$id = $_GET['id'];
$sid = $rows['scparent'];
if ( $id == $sid ) {
?>
<!-- Begin Sub Category List -->
<ul>
<li class="menu"><?php echo $rows['scname']; ?>
</li>
</ul>
<!-- End Sub category List -->
<?php }} ?>
</ul>'
Any help will be appreciated. Thank you
you can try replace your code with this
<?php
$catmenu_sql = 'select category.id AS catid, category.name AS catname, scategory.cparent AS scparent, scategory.name AS scname
from category
left join scategory on category.id = scategory.cparent
group by category.name'; // Select data from database
$result = mysql_query($catmenu_sql);
$sHTML="<ul>";
while($rows = mysql_fetch_assoc($result))
{
$sHTML="<ul>"
<!-- Begin Category list -->
$sHTML .= '<li class="menu">' .
'' . $rows['catname'] .'' .
'</li>' ;
<!-- End Category List -->
$subquery = "SELECT sec_name FROM tbl_user_sec WHERE `sec_group` = '" . mysql_real_escape_string($row_secs['sec_group'] . "'";
$subresult = mysql_query($subquery);
<!-- Begin Sub Category List -->
if (isset($_GET['id']) && is_numeric($_GET['id'])) // get the 'id' variable from the URL and match it with scategory parent in database
$id = $_GET['id'];
$sid = $rows['scparent'];
if ( $id == $sid )
{
$sHTML .="<ul>";
while($row = mysql_fetch_assoc($subresult) ) {
$sHTML .= '<li class="menu">' . $rows['scname'] . '' .
'</li>' ;
}
$sHTML .="</ul>";
}
<!-- End Sub category List -->
}
$sHTML .= '</ul>'
echo $sHTML
?>
If i understand your problem correctly, this line:
if ( $id == $sid ) {
filters the sub categories depending of the page you're, given that $id is being initialized as:
$id = $_GET['id'];
which is the value of a parameter named id that is being passed to the url, possibly like this:
http://www.site.com/script.php?id=1
that's what making you see only a sub set of the categories, to see them all you should not pass the id parameter to the url.

print recursive list in php

I am trying to print a recursive list where every date has a sublist of events ordered by date.
For example on the database I have:
+------+----------+--------+
| date | event_id | post_id|
+------+----------+--------+
|date1 | event1 | post1 |
|date1 | event2 | post2 |
|date1 | event3 | post3 |
|date2 | event4 | post4 |
|date2 | event5 | post5 |
+------+----------+--------+
I need to print
<ul>
<li>date1</li>
<ul>
<li>event1, post1</li>
<li>event2, post2</li>
<li>event3, post3</li>
</ul>
<li>Date 2</li>
<ul>
<li>event4, post4</li>
<li>event5, post5</li>
</ul>
</ul>
how can I print in php the
select date, event_id, post_id from tablename
query in php to have this?
After a while with php and mysql, I do the least I can in mysql, even if it's often more elegant. Performance of mysql is crap. And even if what you query is fast, it can still slow down another query elsewhere done by another user. So here is a response with the least load on the DB. One query, no grouping. just select your 3 fields, and you can apply this.
$lastDate = null; // lastDate will be updated at each row, so we can check if it has changed the next one.
echo '<ul>';
foreach ($queryResult as $row)
{
if ( $lastDate != $row['date'] )
{
if ( $lastDate) { echo '</ul>'; } // if lastdate "exists", it's not the first, so let't close the "date" list...
echo '<li>', $row['date'], '</li><ul>'; // ... and start a new one
}
echo '<li>', $row['event_id'], ', ',$row['post_id'], '</li>';
$lastDate = $row['date'];
}
echo '</ul>'; // close the very last date list
echo '</ul>'; // close the the full list
It looks like you need MySQL GROUP_CONCAT().
SELECT date,
GROUP_CONCAT(event_id) AS 'event_ids',
GROUP_CONCAT(post_id) AS 'post_ids'
FROM tablename
GROUP BY date
This will return results with three fields. date will be the date field, event_ids and post_ids will be comma separated lists of the events and posts that fall under that date.
This should work. You'd want to add some error checking though.
<ul>
<?php
$result = mysql_query(SELECT date FROM tableName);
if (mysql_num_rows($result) > 0)
{
while ($dateRow = mysql_fetch_array($result))
{
echo "<li>" . $dateRow['date'] . "</li>";
$result2 = mysql_query("SELECT event_id,post_id FROM tableName where date = '" . $dateRow['date'] . "'");
if (mysql_num_row($result2) > 0)
{
echo "<ul>";
while ($row = mysql_fetch_array($result2))
{
echo "<li>" . $row['event_id'] . " , " . $row['post_id'] . "</li>";
}
echo "</ul>";
}
}
}
?>
</ul>
The following is a rough answer:
$query = "select date, event_id, post_id from tablename order by date";
$result = mysql_query($query);
$currentDate = null;
echo "<ul>";
while($row = mysql_fetch_assoc($result)){
if($currentDate != $row['date']){
echo "<li>" . $currentDate . "</li>";
echo "<ul>";
}
echo "<li>" . $row['event'] . $row['post'] . "</li>";
if($currentDate != $row['date']){
$currentDate = $row['date'];
echo "</ul>";
}
}
echo "</ul>";
Here's my take on the problem. First of all, you should nest the unordered list items into parent elements. The resulting output should be
<ul>
<li>date1
<ul>
<li>event1, post1</li>
<li>event2, post2</li>
<li>event3, post3</li>
</ul>
</li>
<li>Date 2
<ul>
<li>event4, post4</li>
<li>event5, post5</li>
</ul>
</li>
</ul>
Advantages of this nested schema:
valid html (this alone is good enough)
easier DOM-manipulation by Javascript
Here's a function which in theory should output the former html:
function printList()
{
$sql = 'SELECT t.event_id, t.post_id, t.date FROM table t ORDER BY date';
$result = mysql_query($sql);
$date = null;
$out = '';
while($row = mysql_fetch_assoc($result))
{
if($date !== $row['date'])
{
if(!is_null($date))
{
$out .= '</ul></li>';
}
$date = $row['date'];
$out .= sprintf('<li>%s<ul>', $row['date']);
}
$out.= sprintf('<li>%s, %s</li>', $row['event_id'], $row['post_id']);
}
return sprintf('<ul>%s</ul></li></ul>', $out);
}
$sql = "SELECT date, event_id, post_id
FROM tablename
GROUP BY date ORDER BY date";

Categories