skip to Main Content

Im making a filter where you can select colors and select newest. It would filter them, but the order by doesn’t work for some reason.

I tried it this way. It outputs the colors that match the database table, but it doesn’t sort them by date.

$color_arr = ["red", "blue", "white"];

foreach($color_arr as $color) {
    $data = $conn->query("SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC");
    while ($row = $data->fetch()) {
        print_r($row);
    }
}

2

Answers


  1. Don’t run sql query inside loop.

    $sql = array('0'); // Stop errors when $color_arr is empty
    
    $color_arr = ["red", "blue", "white"];
    foreach($color_arr as $color){
        $sql[] = 'item_color LIKE "%'.$color.'%"';
    }
    
    $sql1 = implode(" OR ", $sql). " ORDER BY `item_date` DESC";
    $sql = "SELECT * FROM `test` WHERE $sql1"; 
    
    $data = $conn->query($sql);
    while ($row = $data->fetch_array()) {
        print_r($row);
    }
    
    Login or Signup to reply.
  2. You can order by multiple fields, below is the MYSQL query:

    SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC, `price` DESC"
    

    This will first sort by item_date and then by price.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search