php mysql : How to list two tables with related data? - php

I had a simple tree structure output question,
In the beginning I use two mysql_query, one is to get the pro_class data, include pro_class.cid , and to query next table by cid, like:
mysql_query("select * from pro_class ");
mysql_query("select * from pro where cid='pro_class.cid' ");
but I want to using one query,how can I accomplish?
table: pro_class
cid  title  time
1  PEOPLE  2013/8/31
4  CAR   2013/8/30
7  Music  2014/7/10
table: pro
id  cid  title  content  time
1  1  Mark xxxx 2010/8/31
2  4  BMW xxxx 2012/2/12
3  1  Joe xxxx 2015/1/31
4  7  sweet xxxx 2013/8/22
5  1  KEN xxxx 2010/1/31
The structure should be
PEOPLE
-Mark
-Joe
-KEN
CAR
-BMW
Music
-sweet
I want to the Html output can like this (by php+mysql)
<ul>
<li class="">PEOPLE</li>
<ul class="sub">
<li><a title='Mark' href='?id=1'>Mark</a></li>
<li><a title='Joe' href='?id=3'>Joe</a></li>
<li><a title='KEN' href='?id=5'>KEN</a></li>
</ul>
<li class="">CAR</li>
<ul class="sub">
<li><a title='BMW' href='?id=2'>BMW</a></li>
</ul>
<li class="">Music</li>
<ul class="sub">
<li><a title='sweet' href='?id=4'>sweet</a></li>
</ul>
</ul>
How do I to coding sql?
$rst = mysql_query("select ?????? ");
while($row = mysql_fetch_object($rst)){
echo <<<EOD
<ul>
<li class="">{$row->pro_class.title}</li>
<ul class="sub">
<li><a title='{$row->pro.title}' href='?id={$row->pro.id}'>{$row->pro.title}</a></li>
</ul>
</ul>
EOD;
}

You can try this approach. It uses group_concat.
<?php
$query = "select pc.title as title, group_concat(p.title) as inner_titles FROM pro_class pc LEFT JOIN pro p ON p.cid=pc.cid GROUP BY p.cid ORDER BY p.title";
$result=mysqli_query($query);
print "<ul>";
while($res=mysqli_fetch_array($result)) {
print "<li>" . $res['title'] . "</li>";
$arr = explode(",",$res['inner_titles']);
if(count($arr)>0) {
print "<ul>";
foreach($arr as $val) {
print "<li>" . $val . "</li>";
}
print "</ul>";
}
}
print "</ul>";
?>

You can use a mysql function called group_concat which will merge a number of rows into a string that is delimited by something you choose.
The following will get you most of the way to getting what you want - you can probably work out the display part on your own though.
select
pro_class.title,
GROUP_CONCAT(pro.title SEPARATOR ',') AS listItems
from
pro_class
left outer join pro
on pro_class.cid=pro.cid
group by
pro_class.title

Related

How can I return data from MySQL as navbar links [duplicate]

This question already has an answer here:
Struggling to output PHP array as unordered HTML list
(1 answer)
Closed 2 years ago.
I want to return some data from my table as navbar links, my table holds this information:
Then I coded this:
<?php
$result = $db->query("SELECT * FROM topnav ORDER BY 'table_id' ASC");
while($row = $result->fetch_object()){
echo "
<li><a href='contact.html'>".$row->name_link."</a></li>
<li><a href='about.html'>".$row->name_link."</a></li>
<li><a href='news.html'>".$row->name_link."</a></li>
<li><a href='news.html'>".$row->name_link."</a></li>
<li><a href='news.html'>".$row->name_link."</a></li>
<li><a href='blog.html'>".$row->name_link."</a></li>
<li class='active'><a href='index.html'>".$row->name_link."</a></li>
";
}
?>
But this is wrong because it prints this as result:
And I want each item to be printed once and then another name_link appears.
So how can I do that?
Assuming the value from name_link column is the same of html file, then:
<?php
$result = $db->query("SELECT * FROM topnav ORDER BY 'table_id' ASC");
while($row = $result->fetch_object()){
echo "<li><a href='".$row->name_link.".html'>".$row->name_link."</a></li>";
}
?>
This would seem to be more like what you need - create one <li> per row returned from your table. (I've assumed href-link is the field in your table which should be used as the URL.)
<?php
$result = $db->query("SELECT * FROM topnav ORDER BY 'table_id' ASC");
while($row = $result->fetch_object()){
echo "<li><a href='".$row->href_link."'>".$row->name_link."</a></li>";
}
?>
What you were doing before is repeating your entire menu for every row in your table, which doesn't make any sense.

drop down menu from database

I am want to make a navigation menu with a sub menu on hover. I want to get this data from my database (to make it dynamic if data in database changes menu bar changes). In my database I have a table with the the following fields:
ID, Name, Level, Parent_id. Level can be 0 or 1. 0 for main menu 1 for sub menu the id of a main menu is tied to the parent_id field.
So for instance:
ID Name Level Parent_id
1 Test 0
2 Test2 0
3 Test_sub 1 1
4 Test_sub2 2 2
I have managed to get the main menu items from the db but now I am a little bit stuck. This is my code any help would be appriciated.
<?php
$q2= "SELECT * from menu where level = 0 ";
$q2result = $db->query($q2);
while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
echo "
<ul>
<li><a href='#' ><span> " . $a2['name'] . " </span></a>
<ul>
<li><a href='#' ><span> test </span></a></li>
</ul>
</ul>
";
}
?>
First load all your datas into variables. Never print/echo while in SQL statement.
<?php
$q2= "SELECT * FROM menu ORDER BY Level ASC";
$q2result = $db->query($q2);
$nodes=array();
while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
// assuming one parent node has already been assigned, due do level order into the SQL
if($node['Level']>0 && isset($nodes[$a2['id']])) {
$nodes[$a2['id']]['nodes'][]=$a2;
} else {
// parent node
$nodes[$a2['id']]=$a2;
$nodes[$a2['id']]['nodes']=array();
}
}
print "<ul>";
foreach($nodes as $node) {
print "<li>";
print "<a href='#'>".$node['Name']."</a>";
if(sizeof($node['nodes'])>0) {
print "<ul>";
foreach($node['nodes'] as $subnode) {
print "<li><a href='#'>".$subnode['Name']."</a></li>";
}
print "</ul>";
}
print "</li>";
}
print "</ul>";
?>
This may be much more improved, but with this, you can do what you ask, and improve it.

How do you populate tabs in sequence from database using PHP?

This is probably an easy question but does anyone know how to insert data from a database into tabs autonomously ordered by a certain field?
Let me clarify, I need each tab to display data from my database ordered by the date they were added. So the latest in tab 1, the next in tab 2, and so on.
I've had this working in an accordion style where I did the database query first with a limit of five which repeated my code that inserted the info from the database up to five times. I have been trying to figure out a way similar to this except with tabs instead. Even if I could get a database query to put the latest result in tab 1, then do another query in tab 2 to find the second newest result, and so on.
Thanks for your time. Sorry if this is a silly question. :)
Sorry for leaving out code. What I am hoping to do is to call data from a database with code simular to
<?php
$subject_set = mysql_query("Select * FROM database WHERE column1 like 'value' ORDER BY date_added DESC LIMIT 4", $connection);
if (!$subject_set){
die("Database connection failed: " . mysql_error());
}
while ($subject = mysql_fetch_array($subject_set)){?>
<ul class="tab-links">
<li class="active">Tab #1</li>
<li>Tab #2</li>
<li>Tab #3</li>
<li>Tab #4</li>
</ul>
<div class="tab-content">
<div id="tab-1" class="tab active">
<?=$subject['column1']?>
<?=$subject['column2']?>
<?=$subject['column3']?>
<?=$subject['column4']?>
</div>
<div id="tab-2" class="tab">
<?=$subject['column1']?>
<?=$subject['column2']?>
<?=$subject['column3']?>
<?=$subject['column4']?>
</div>
<div id="tab-3" class="tab">
<?=$subject['column1']?>
<?=$subject['column2']?>
<?=$subject['column3']?>
<?=$subject['column4']?>
</div>
<div id="tab-4" class="tab">
<?=$subject['column1']?>
<?=$subject['column2']?>
<?=$subject['column3']?>
<?=$subject['column4']?>
</div>
</div>
I was hoping for code similar to this or probably only have one tab which is repeated depending on the limit in the database query.
First, the query:
SELECT column1, column2 FROM tableName ORDER BY dateColumn DESC LIMIT 5;
Let's assume you put this data into an array called $data.
If your tabs are HTML <li> elements then you can create a function for creating the HTML:
function buildList($data){
$output = "";
if(!empty($data)){
$output .= "<ul>";
foreach($data as $row){
$output .= "<li>" . $row . "</li>";
}
$output .= "</ul>";
}
return $output;
}
I don't think I can provide any more detail without knowing the structure of your table, or the expected output.

Dynamic Drop Down Menu and submenu php mysql

I have a menu that needs to be created dynamically from the database.
need to have menu and submenu
for example (wht i want):
<ul class="dropdown">
<li>Link 1 </li>
<li>Link 2 </li>
<li>Link 3 </li>
<li>Link 4
<ul class="sub_menu">
<li>Link 4 - 1</li>
<li>Link 4 - 2</li>
<li>Link 4 - 3</li>
</ul>
</li>
<li>Link 5</li>
<li>Link 6 </li>
</ul>
below is the code i used for menu using function i want submenu as well
function listMenu(){
$ans = $this->select("cat_id,cat_name","s_category","1");
if(is_array($ans)){
foreach($ans as $val){
echo
"<li><a href=\"post-summary.php?cid=$val[0]\" >$val[1]</a></li>";
}
}
else{
echo "";
}
}
database is as follows:-
CREATE TABLE IF NOT EXISTS `s_category` (
`cat_id` int(11) NOT NULL AUTO_INCREMENT,
`cat_name` varchar(15) NOT NULL,
`cat_uid` int(2) NOT NULL,
`cat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`cat_parent` int(11) DEFAULT '0',
`cat_sort` int(11) DEFAULT NULL,
`cat_delete` int(1) DEFAULT '0',
PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
You need to have a column, let we name it parentId in the s_category table.
Example values in there:
catId,catName,parentId
1,Vehicles,null
2,Planes,null
3,Cars,1
4,Bicycles,1
So your structure will be like:
- Vehicles
- Cars
- Bicycles
- Planes
You'll need to get the data like this (to be considered as pseudocode):
$topLevelItems = (select catId, catName from s_category where parentId is null)
foreach($topLevelItems as $item) {
echo '$item["catName"]';
$subItems = (select catId, catName from s_category where parentId=$item['catId'])
foreach($subItems as $subItem) {
echo '$subItem["catName"]';
}
}
You need to re-write the SQL part to match your case. This will work if you have just one inner level, e.g. no sub-sub-menus. If you plan to use sub-sub-menus you'll need recursive function.
as far as menus are concerned storing the submenus as a comma seperated values in the database would come handy.
ie consider a table with id,menus,submenus(several submenus seperated by a comma).
function listMenu(){
$ans = $this->select("menus,submenus");
if(is_array($ans)){
foreach($ans as $val){
echo "<li><a href=\"post-summary.php?cid=$val[0]\" >$val[0]</a>"; //menus
$submenu = explode(",",$val[1]);
foreach($submenu as $values){
echo "<li><a href=\"post-summary.php?cid=$val[0]&proname=$values\" >$values</a></li>"; // submenus
}
echo "</li>";
}
}
}
try this
$con = db_connect();
$str = "select menus,submenus from your_tabel ";
$result = mysql_query($str,$con);
while($arr = mysql_fetch_array($result))
{
echo "<li><a href=\"post-summary.php?cid=$arr[0]\" >$arr [0]</a>"; //menus
$submenu = explode(",",$arr [1]);
//make sure you have several sub-menus else use a if condition here to avoid foreach error
foreach($submenu as $values){
echo "<li><a href=\"post-summary.php?cid=$arr[0]&proname=$values\" >$values</a></li>"; // submenus
}
echo "</li>";
}
this works fine for me just tested now
comment if working.
comment if not-working.
created your database and write function with code and change parameters
function getAllFrom($field, $table,$where = NULL, $and = NULL , $orderfield, $ordering = "DESC") {
global $con;
$getAll = $con->prepare("SELECT $field FROM $table where $where $and ORDER BY $orderfield $ordering");
$getAll->execute();
$all = $getAll->fetchAll();
return $all;}
<ul>
<?php
$allCats = getAllFrom("*", "categories", "parent = 0", "" , "cat_id", "ASC");
foreach ($allCats as $cat) { ?>
<li>
<?php
echo '<a href="categoreis.php?pagename=' . str_replace(' ', '-', $cat['name_cat']) . '&pageid=' . $cat["cat_id"] . '">
' . $cat['name_cat'] . '
</a>';
?>
<ul class="sub-menu[enter image description here][1]">
<?php
$catsub = $cat['cat_id'];
$SubCats = getAllFrom("*", "categories", "parent = {$catsub}", "" , "cat_id", "ASC");
foreach ($SubCats as $sub) { ?>
<li>
<?php
echo '<a href="categoreis.php?pagename=' . $sub['name_cat'] . '&pageid=' . $sub["cat_id"] . '">
' . $sub['name_cat'] . '
</a>';
?>
</li>
<?php }
?>
</ul>
</li>
<?php }
?>
</ul>

Multilevel menu from database records

I need some help with PHP. I have a multilevel css menu that works fine, but now I want to generate according to the records from a database.
The menu Code:
<div id="page-wrap">
<ul class="dropdown">
<li>Link 1 </li>
<li>Link 2 </li>
<li>Link 3 </li>
<li>Link 4
<ul class="sub_menu">
<li>Link 4 - 1</li>
<li>Link 4 - 2</li>
<li>Link 4 - 3</li>
</ul>
</li>
<li>Link 5</li>
<li>Link 6 </li>
</ul>
</div>
In the database every record has a field called main_manu which makes it a main link if the value of this field is Yes, and if the value is No then it has another field (sub_menu) which says the parent menu in which this link should be placed.! See the screenshot.
DB Fields
SO, now I don't know how to do the php piece that will get the records and if the value of the main_menu is yes, it will create a top level menu, and if the value of main_menu is no, it will create a sub level menu according to the value of sub_menu field.
Thanks a lot
UPDATE
This is the code I have so far and it works. It would be nice if I could use a single query instead of multiple nested queries.
<div id='page-wrap'>
<ul class='dropdown'>
<?
$sql_menu = "SELECT * FROM content WHERE visible = '1' and main_menu='yes' ";
$result_menu = mysql_query($sql_menu);
while($row = mysql_fetch_assoc($result_menu))
{
$id=$row['id'];
$menu_top=$row['menu_name'];
$menu_url=$row['menu_url'];
print "<li><a href='$menu_url'>$menu_top</a>";
$sql_sub = "SELECT * FROM content WHERE sub_menu = '$menu_url' ";
$result_sub = mysql_query($sql_sub);
$num_rows = mysql_num_rows($result_sub);
while($row = mysql_fetch_assoc($result_sub))
{
$id=$row['id'];
$menu_sub=$row['menu_name'];
$sub_url=$row['menu_url'];
If ($num_rows != 0)
{
print "<ul class='sub_menu'>
<li><a href='$sub_url'>$menu_sub</a></li>
</ul>";
}
}
print "</li>";
}
?>
</ul>
</div>
The code for this would be something like the following (This will need to be changed for whatever way you interact with the database etc.):
// Here we do a query to get all the rows from the table
$db_result = db_execute_query('SELECT * FROM `menu_table` ORDER BY `order_no`');
// Here we take the rows and put it into a structured array
$items = array();
$hierarchy = array('' => array());
while ($row = db_fetch_row($db_result)) {
$items[$row['menu_name']] = $row['menu_name_en'];
if ($row['main_menu'] == 'yes') {
$hierarchy[''][] = $row['menu_name'];
} else {
if (!isset($hierarchy[$row['sub_menu']]) {
$hierarchy[$row['sub_menu']] = array();
}
$hierarchy[$row['sub_menu']][] = $row['menu_name'];
}
}
// Here we define a recursive function to run through our $hierarchy array;
function show_menu($name = '') {
if (isset($hierarchy[$name])) {
if ($name == '') {
echo '<ul class="dropdown">';
} else {
echo '<ul class="sub_menu">';
}
foreach ($hierarchy[$name] as $sub) {
echo '<li>' . $items[$sub] . '';
show_menu($sub);
echo '</li>';
}
echo '</ul>';
}
}
// Here we execute the recursive function on the main menu
show_menu('');
Try to understand what I'm doing here instead of just implementing it verbatim. Once you get to know recursive functions, a whole new world can open for you.
Also note that your db table could be changed to make this code simpler
I think these link will help you out. if not please let me know i will give you the code
http://board.phpbuilder.com/showthread.php?10337808-how-to-create-menu-submenu-subsubmenu-using-php-mysql
http://www.sitepoint.com/forums/showthread.php?718237-how-to-create-dynamic-menu-and-submenu-using-php-and-mysql

Categories