Having an issue with a query..my wscategories stores the main categories of an online store, and my wssubcategories table stores the sub categories of the table with the foreign key called "parentcategory". I'm trying to list the main categories, with the subcategories underneath a la:
Tops
T-Shirts
Wovens
Sweaters
Pants
Shorts
Jeans
The query/result I wrote is the following:
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['maincategory'];
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
}
Which returns:
Tops
T-Shirts
Tops
Sweaters
Tops
Wovens
Etc. I want the script to just display the main category once, and then the subcategories underneath vs. displaying it multiple times. Any help?
try something like this
// note we need to order by maincategory for this to work
//
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id
ORDER BY maincategory ASC,
smallcategory ASC
";
$result = mysql_query($query) or die(mysql_error());
// keep track of previous maincategory
$previous_maincategory = NULL;
while ($row = mysql_fetch_assoc($result))
{
// if maincategory has changed from previouscategory then display it
if ($previous_maincategory != $row['maincategory']) {
echo $row['maincategory'];
}
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
// record what the previous category was
$previous_maincategory = $row['maincategory'];
}
Set a flag after you echo the main category, like this:
$echoed_main = false;
while ($row = mysql_fetch_array($result)) {
if (!$echoed_main) {
echo $row['maincategory'];
echo "<br/>";
$echoed_main = true;
}
echo $row['smallcategory'];
echo "<br/>";
}
Related
With this I get:
Category 1
Product
Category 1
Product
Category 2
Product
etc...
Here is my new query:
<?php
$oldcat = "";
$sql_cat = "SELECT coupons_category.category_id, coupons_category.category_name, coupons_coupons.coupon_category, coupons_coupons.coupon_name, coupons_coupons.prezzo_reale, coupons_coupons.coupon_realvalue, coupons_coupons.acconto,coupons_coupons.gratis,coupons_coupons.coupon_startdate,coupons_coupons.coupon_image,coupons_coupons.coupon_enddate, coupons_coupons.meta_title,coupons_coupons.coupon_id FROM coupons_category LEFT JOIN coupons_coupons ON coupons_category.category_id=coupons_coupons.coupon_category ORDER BY coupons_category.category_name";
$result_cat = mysqli_query($conn, $sql_cat);
if (mysqli_num_rows($result_cat) > 0) {
while($row_cat = mysqli_fetch_assoc($result_cat)) {
if ($oldcat != $row_cat['category_id'] ) {
if ($oldcat != "") echo "<br />";
echo "".$row_cat['category_name']."<br />";}
echo "". $row_cat['coupon_name']."";
$oldcat = $row_cat['category_id'];
}
}
I think you need to do a single query, and check to see when the category changes in your loop code. Something like:
$oldcat = "";
$q = "select * from product where status = 'A' left join category on category.category_id = product.category order by category";
; execute the query
; while $row = mysqli_fetch_assoc($result) {
if ($oldcat != $row['category'] ) {
if ($oldcat != "") echo "<br />";
echo $row['category.category_name'] . "<br />";
}
echo $row['product_name'];
$oldcat = $row['category'];
}
That's pseudo-code, so I've missed out all the irrelevant bits like executing the query, checking it worked, converting the product name and so on. But the idea is that each time you retrieve a row, you check to see if the category changed, and if it did, display the new category name.
My question is how to get multiple images to display next to their respective units information. I am able to print out all the images below but unable to get each listing to print out its respective images. originally i was trying to do it as a single query but it was only printing out the same image multiple times so i tried to do two seperate queries but it did not work, how can i fix it?
// Define the query but only for info:
$querystats = 'SELECT 8052monticello.UNIT, 8052monticello.SIZE, 8052monticello.id, 8052monticello.PRICE';
$querystats.= ' FROM 8052monticello';
if ($r = mysqli_query($connection, $querystats)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['PRICE']){
// echo "<img src='images/".$row['image_name']."' width='100'>";
print "<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
}
//get the images
$queryimage = 'SELECT photos.image_name, photos.fk_unit, 8052monticello.UNIT';
$queryimage.= ' FROM photos, 8052monticello';
$queryimage.= ' WHERE photos.fk_unit= 8052monticello.unit';
if ($r = mysqli_query($connection, $queryimage)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['image_name']){
echo "<img src='images/".$row['image_name']."' width='100'>";
}
}
}
You can use a JOIN in your query to join both the monticello and photos table:
$query = '
SELECT
m.UNIT, m.SIZE, m.id, m.PRICE,
p.image_name
FROM 8052monticello m
INNER JOIN photos p ON p.fk_unit = m.unit';
Now you have access to $row['image_name'] in your loop.
while ($row = mysqli_fetch_assoc($r)) {
if ($row['PRICE']){
print "<img src=\"images/{$row['image_name']}\" width='100'>
<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
Updated: For each row, images are fetched from the database.
$query = "SELECT
m.UNIT, m.SIZE, m.id, m.PRICE
FROM 8052monticello m ";
$res = mysqli_query($connection, $query);
if (!$res){
// throw error here
}
$query2 = "SELECT p.image_name
FROM photos p
WHERE p.fk_unit = '%s' ";
while ($row = mysqli_fetch_assoc($res)) {
$res2 = mysqli_query($connection, sprintf($query2, $row["UNIT"]));
while($img = mysqli_fetch_assoc($res2)) {
echo "<img src=\"images/{$img['image_name']}\" width='100'>";
}
print "<p><h3>{$row['UNIT']} Unit #</h3>
{$row['SIZE']} Sq Feet<br>
{$row['PRICE']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
// PAGE ONE
This is the index page, Here I am printing out rows from a list of
movie´s with some basic info, title , year.
I am also adding edit and delete links to the movies,
these work by passing the row id's of that movie.
$sql = "SELECT c.* , d.* FROM category c , movies d WHERE c.ID=d.ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='floatbox collection'><table><tr><th>Titel</th><th>regissör</th><th>År</th><th>Genre</th><th>Ändra</th><th>Ta bort</th>";
while($row = $result->fetch_assoc()) {
echo
"<tr><td>".$row["title"]."</td><td>".$row["director"]."</td><td>"
.$row["year"]."</td><td>".$row["category"]."</td>
<td><a href='edit.php?row=".$row["ID"]."'>justera</a></td>
// delete link to send ID to next page
<td><a href='delete.php?delete=".$row["ID"]."'>stryk</a></td>";
}
echo "</table></div>";
} else {
echo "0 results";
}
// PAGE TWO
Here I have my $row[ID] trough $_get by the link on the previous page,
I have checked the value by "dumping" so I know that the row ID is in that
variable: The thing is, How do I call that $ID in my sql statement?
I'm trying to delete by calling that ID on the table row.
// Variable with correct ID value
if(isset($_GET["ID"]))
if($_GET["ID"]) = $ID; // This doesn't work, Do I need to convert
the $get_ID to a variable with the ID that can be called in the statement?
or is my syntax wrong?
// Delete join
$sql = "SELECT * FROM movies, category
INNER JOIN category ON movies.ID = category.ID
DELETE WHERE movies.ID = '$ID'"; // No syntax works here
// Any help appreciated.
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br>
<a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
As per your code your delete.php would be like this:
// Variable with correct ID value
if (isset($_GET["delete"])) {
$ID = $_GET["delete"];
// Delete join
$sql = "DELETE FROM movies, category INNER JOIN category ON movies.ID = category.ID WHERE movies.ID = '$ID'";
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br><a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
}
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>";
}
}
I am trying to code a hierarchy detection script, I've already written the script, but can only go down 4 levels. Is there a way to condense this to a few lines that will work with an infinite amount of levels?
This script is basically the same code copy and pasted 4 times
<?php
function listCategories($name, $disable_status = 0, $show_nums = 0) {
echo "<select name='".$name."'>";
$result = mysql_query("SELECT * FROM categories") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if($row['parent_id']==0) {
$result2 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row['id']) or die(mysql_error());
echo "<option value='".$row['id']."'";
if($disable_status==1&&isParent($row['id'])){
echo " disabled='disabled'";
}
echo ">".$row['name']."</option>";
while($row2 = mysql_fetch_array($result2)) {
$result3 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row2['id']) or die(mysql_error());
echo "<option value='".$row2['id']."'";
if($disable_status==1&&isParent($row2['id'])){
echo " disabled='disabled'";
}
echo ">- ".$row2['name']."</option>";
while($row3 = mysql_fetch_array($result3)) {
$result4 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row3['id']) or die(mysql_error());
echo "<option value='".$row3['id']."'";
if($disable_status==1&&isParent($row3['id'])){
echo " disabled='disabled'";
}
echo ">-- ".$row3['name']."</option>";
while($row4 = mysql_fetch_array($result4)) {
echo "<option value='".$row4['id']."'>[".$row4['id']."] --- ".$row4['name']."</option>";
}
}
}
}
}
echo "</select>";
}
function isParent($cat_ID) {
$result = mysql_query("SELECT * FROM categories WHERE parent_id=".$cat_ID) or die(mysql_error());
if(mysql_num_rows($result)==0) {
return FALSE;
} else {
return TRUE;
}
}
My table structure for categories is
id, name, parent_id
If the category has no parent, the parent_id will be 0, or else, it would be the id of the category of it's parent.
All help is appreciated.
I guess something along these lines should do (untested, must be adapted to your needs):
$q = mysql_query("SELECT id, parent_id, name FROM categories");
while ($r = mysql_fetch_row($q)) {
$names[$r[0]] = $r[2];
$children[$r[0]][] = $r[1];
}
function render_select($root=0, $level=-1) {
global $names, $children;
if ($root != 0)
echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
foreach ($children[$root] as $child)
render_select($child, $level+1);
}
echo '<select>';
render_select();
echo '</select>';
an even funkier way of doing this is by using SQL stored procedures, but it may be way overkill in this case...
This isn't an answer but instead of using many selects you can use many left joins to traverse 4 hierarchies. Instead of so many row of codes it's just this single query:
select a.id,a.parent_id,b.id,b.parent_id,c.id,c.parent_id,d.id,d.parent_id from a left join b ON a.id = b.parent_id left join c on b.id=c.parent_id left join d on c.id=d.parent_id;
You can use my query with a single table, too, because you can alias a table name:
left join mytable as c on c.id=d.parent_id ... ...
But unfortunetley mysql doesn't support recursive selects. Maybe try another database?