I'm using the following not well thought code block to retrieve categories and it's topics.
$query1 = "SELECT * from categories";
$result = mysql_query($query1);
while ($out = mysql_fetch_assoc($result)){
//category
print '<h2>' . $out['name'] . '</h2>';
$query2 = "SELECT * from topics where fkid = $out[id]";
$result2 = mysql_query($query2);
while($top = mysql_fetch_assoc($result2)){
//topic
print $top['name'] . '<br>';
}
}
The above does the trick. I know this is not the most practical and this being the reason I ask the group.
How can I better this so it's more practical and simple?
A classical case for a JOIN:
SELECT * FROM categories JOIN topics ON categories.id = topic.fkid ORDER BY categories.name;
Then to print, we only print the header if it has changed (thanks, Rajasur!):
$catname = "";
while ($out = mysql_fetch_assoc($result))
{
if ($out["name"] != $catname) // maybe need strcmp here
{
$catname = $out["name"];
print($catname)
}
/* print the rest */
}
Just use a single query that joins the two tables.
$query = "SELECT categories.name AS category_name, topics.name AS topic_name
FROM categories JOIN topics ON categories.id = topics.fkid
ORDER BY categories.name ASC, topics.name ASC";
$resultSet = mysql_query($query);
$currentCategory = "";
while ($cRecord = mysql_fetch_assoc($resultSet)) {
if ($currentCategory != $cRecord['category_name']) {
$currentCategory = $cRecord['category_name'];
echo "<h2>" . $currentCategory . "</h2>";
}
echo $cRecord['topic_name'] . "<br/>";
}
mysql_close($resultSet);
Related
I have a web page that is divided into different sections. Each section has to show different results. These results are gotten from the database.
This is a sample data on SQLfiddle
http://sqlfiddle.com/#!9/ad98b/1
The following code is what comes to my mind but I'm afraid that it might somehow overload the server when this page is accessed multiple times by different people
$sectionA = $connect->query("SELECT * FROM Main_Section WHERE section = `A`
");
while ($row = $sectionA->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_a = $sec_result_a.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
$sectionB = $connect->query("SELECT * FROM Main_Section WHERE section = `B` ");
while ($row = $sectionB->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_b = $sec_result_b.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
$sectionC = $connect->query("SELECT * FROM Main_Section WHERE section = `C` ");
while ($row = $sectionC->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_c= $sec_result_c.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
UP TO section Z
Is there a way I can Optimise this properly?
Unless there's more to the picture, why not just query everything, ordered by section, to have the A-Z:
SELECT * FROM Main_Section ORDER BY section
... and then process the results with one loop, which could look something like this:
$sections = $connect->query("SELECT * FROM Main_Section ORDER BY section");
while ($row = $sections->fetch_array())
{
echo $row['section'] . ' ' . '<p>' . $row['id'] . '</p><h3>' . $row['firstname'] . ' ' . $row['lastname'] . '</h3>';
}
I am trying to create dynamic menu using the below code, but it takes too much time to load:
<?php
ob_start();
include ('admin/db/db.php');
echo '<li>Exports';
$sql3 = "SELECT * FROM category_master where type = 'Export' order by sequence asc ";
$result3 = mysqli_query($connection, $sql3);
if (mysqli_num_rows($result3) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows3 = mysqli_fetch_assoc($result3))
{
$cid = $userrows3['product_category_id'];
$cname = $userrows3['category_name'];
echo '<li>' . $cname . '';
$sql4 = "SELECT group_product FROM products,category_master,cat_wise_pro where category_master.product_category_id = cat_wise_pro.category_id and products.product_id = cat_wise_pro.product_id and category_master.product_category_id =$cid group by products.group_product ";
$result4 = mysqli_query($connection, $sql4);
if (mysqli_num_rows($result4) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows4 = mysqli_fetch_assoc($result4))
{
$gname = $userrows4['group_product'];
echo '<li>' . $gname . '';
$sql5 = "SELECT product FROM products,group_products where products.group_product = group_products.group_product and products.group_product = '$gname'";
$result5 = mysqli_query($connection, $sql5);
if (mysqli_num_rows($result5) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows5 = mysqli_fetch_assoc($result5))
{
$pname = $userrows5['product'];
echo '<li>' . $pname . '';
}
echo '</ul>';
}
}
echo '</ul>';
}
}
}
echo '</ul>';
?>
should i use view instead of table...find below the view i create
Any ideas how to make it faster?
What your code does is:
categories = load C categories from DB
foreach category:
groups = load G groups from DB
foreach group:
products = load products from DB
which sends 1 + C x G queries to database. What you should do is:
products = load products with groups with categories
$tree = [];
foreach ($products as $p):
$tree[$p['category']][$p['group']][] = $p;
foreach ($tree as $category => $groups):
foreach ($groups as $group => $products):
foreach ($products as $p):
...
Use JOIN to fetch the data at once, e.g. something like:
SELECT p.name as product, g.name as group, c.name as category
FROM product p
JOIN group_product g ON p.group_product = g.id
JOIN category_master c ON g.category = c.id;
I have a table in database as "neotheme_blog_post" and there are many post in there, now i want to fetch recent 3 posts from this table and show them on home page: I have tried to fetch the data as follows but nothing worked:
<?php $connection =
Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM 'neotheme_blog_post'";
$rows = $connection->fetchAll($query);
foreach ($rows as $values) {
echo $name = $values['name'];
}?>
You may use LIMIT over here.
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM neotheme_blog_post LIMIT 3";
$rows = $connection->fetchAll($query);
foreach ($rows as $values){
echo $name = $values['name'];
}
In my case i get the three recent posts as like follows using neotheme blog extension:
$connection =
Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "Select * FROM neotheme_blog_post ORDER BY created_at DESC LIMIT 3 ";
$rows = $connection->fetchAll($query);
foreach ($rows as $values) {
$post_titile = $values['cms_identifier'];
echo '<div>';
echo '<h1>' . $name = $values['title'] . '</h1>';
echo $summery = $values['summary'];
echo 'Read More';
echo '</div>';
Hello im learning so im sorry if this is a fool question. (also sorry about my bad english)
Im trying to display the items from a particular category.
In my Database, i have set my categories like this.
And the Products or Items like this,
Im using this code to display tree categories.
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$list = '<li>'.$parent['name'].'</li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
But i cant find a good way to convert the categories in links, so each time a users clic one category i will display the items for that category..
What would be the best for that.
If you can point me in the right direction, some tutorial, or something, would be really , really great.
It sounds like you are looking for some sort of java tree viewer, like this example?
http://dftree.sourceforge.net/dftree/example.html
There are several open source options for this (I have no experience of the one I list above, I just use it as an example). I'm sure I have used a tree viewer in the past that took a list format like you are using - I suggest you have a search around sourceforge.
Your question is not foolish, but is quite long... and many of us are quite lazy :-)
Ok i solve this
This is the code for the page with the menu and categories
<?php
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$productpage = "index.php";
$list = '<li><a href='.$productpage.'?'.'cat='.$parent['id'].'>'.$parent['name'].'</a></li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
?>
And the code for the product page
<?php
$producto = mysql_escape_string($_GET['producto']);
$tablename = "productos";
$res = mysql_query("SELECT * FROM `$tablename` WHERE `id` = '$producto'");
$row = mysql_fetch_assoc($res);
$uid = $row["id"];
$titulo = $row["titulo"];
$descripcion = $row["descripcion"];
$modelo = $row["modelo"];
$img = $row["img"];
// echo the output to browser or compound an output variables here
echo "ID = $uid
<br />Titulo = $titulo
<br>Descripcion = $descripcion
<br>Modelo = $modelo
<br>Imagen = <img src=\"../admin/$img\" width=\"40px\" height=\"40px\" >
<hr />";
?>
I want to make a Navigation with 2 levels.
My Code so far
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
foreach ($list as $kat) {
echo '<li>' . $kat['name'] . '</li>';
}
?>
Nested Sets are at the moment too tricky for me.
I want at the end this.
<li>$kat['name']
<li>$kat['name'] from PID</li>
</li>
MySQL:
http://i46.tinypic.com/35052m0.png - IMG
No I want to get the things our of the MySQL DB see the image Link.
MySQL:
id—–pid——name
1——0——–name1
2——0——–name2
3——0——–name3
4——3——–name3.1
5——3——–name3.2
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[$row['id']] = $row;
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='".$row['id']."' ORDER BY name");
$res = mysql_query($sql);
while($rw = mysql_fetch_assoc($res)){
$list[$row['id']]['sub'][] = $rw;
}
}
echo "<pre>";
print_r($list);
?>