简体   繁体   中英

How to sort and display database results with MySQL/PHP

I am using PHP to sort items on my website into different locations/different divs. I have a script in each div where I want the results to be displayed So if there are 4 divs there are 4 scripts. (4 categories) Each script has a query in the head of my page.

MySQL query for category/div 1

$sql_category1 = <<<SQL
  SELECT *
  FROM `list_items`
  WHERE `category` = 1 
  ORDER BY `rating` ASC;
SQL;

if(!$category1 = $db->query($sql_category1 )){
    die('There was an error running the query [' . $db->error . ']');
}

My PHP for category/div 1:

<?php 
    while($row = $category1->fetch_assoc()) {

    '<div class="list-item-container">'
    . '<a href="' . $row['url'] . '"><img title="' . $row['title'] . '" class="favicon" src="http://www.google.com/s2/favicons?domain='. $row['fav_url'] . '" /></a>'
    . '</div>';

}
?>

My goal: When i am entering data into the table and there are two items that can be classified as two different things, so two different categories, I have to make two copies of it. This way a item will appear in both categories. Same item two different categories. I give one of the items a category value of 1 and the other item a category value of 2.

Rather than making two separate entries of the same item is there a way that I can give that item two separate category values? This way the item will appear in both categories when my scripts run and sort them.

I tried 1,2 1:2 and 1;2 as the value of the item. Tho im sure it's not even close to that.

Thanks in advance!

make 3 tables:

category (id, name, ...)

item (id, name, ...)

item_category (id_item, id_category)

them make join of them in your queries, eg your first query will become

SELECT *
FROM `list_items` t,`item-category`
WHERE `id_category` = 1
  and `id_item` = t.`id`
ORDER BY `rating` ASC;

After you have connection table you can put in it whatever connections you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM