简体   繁体   中英

PHP, SQL: How to use WHERE field in Query to get multiple values?

I have a database with prices of mangos, apples, and oranges, arranged by date.

I want to filter the prices in a table by ID. I'm able to filter the results using one ID, and display them in a table.

How can I filter by more than one ID value using WHERE in SQL, and display the resulting data in tabular form?

<table style="float:left;">
  <tr>
    <th>Mango </th>
    <th>Apple</th>
    <th>Orange </th>
    <th>Date</th>

  </tr>
  <?php
  $dbhost ="localhost";  // hostname
  $dbuser="root"; // mysql username
  $dbpass="****"; // mysql password
  $db="****"; // database you want to use
  $conn= mysqli_connect( $dbhost, $dbuser, $dbpass, $db ) or die("Could not connect: " .mysqli_error($conn) );
  $sql = "SELECT MANGO, APPLE, ORANGE, DATE FROM dataTable WHERE ID='3' ORDER BY Date DESC LIMIt 1";
  $result = $conn->query ($sql);
  if($result ->num_rows>0){
    while($row = $result ->fetch_assoc()){
      echo "<tr><td>". $row["MANGO"]."</td><td>".$row["APPLE"]."</td><td>".$row["ORANGE"]."</td><td>".$row["DATE]."</td> </tr>";
    }
    echo "</table>";
  }else {echo "0 result";}
  $conn->close();
   ?>
</table>


Consider using the IN operator to filter using a sequence of ID values.

For example, if you want to get results where ID=1 or ID=2 or ID=3 :

$sql = "SELECT MANGO, APPLE, ORANGE, DATE FROM dataTable WHERE ID IN (1,2,3) ORDER BY Date DESC";


Please see Select Multiple Ids from a table , for more information.

You can also check out more information on the IN operator here .

您可以这样执行: SELECT MANGO, APPLE, ORANGE, DATE FROM dataTable WHERE ID='3' OR ID='4'并且您可以根据需要添加任意多个OR

Your table design is broken. The fruits are not supposed to be columns.

Databases like their data nicely separated, with relations expressed through internal keys (primary key, foreign key). If you do that, they will be superfast and reliable in finding it, even if you have hundred thousands of records stored.

table "fruits"
id | name
 1, 'Mango'
 2, 'Orange'
 3, 'Apple'

table "fruits_date_prices"
id | fruit_id | price | date   
 1, 1, 1.30, '2019-03-20'
 2, 1, 1.35, '2019-03-21'
 3, 1, 1.37, '2019-03-22'
 4, 2, 0.87, '2019-03-20'
 5, 2, 0.86, '2019-03-21'
 6, 2, 0.84, '2019-03-22'
 7, 3, 0.34, '2019-03-20'
 8, 3, 0.36, '2019-03-21'
 9, 3, 0.35, '2019-03-22'

Query for prices on a day, using a JOIN (eg. "two tables in one call"):

SELECT
    f.name AS fruit,
    fdp.price 
FROM 
    fruits AS f
LEFT JOIN
    fruits_date_prices AS fdp ON f.id = fdp.fruit_id
WHERE
    fdp.date = '2019-03-21'

Hope that helps a bit :)

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