如何根据列值MySQL和PHP过滤表中的数据

时间:2016-07-12 05:53:47

标签: php mysql

我需要使用PHP和MySQL根据列值从表中获取数据。我在解释下面的表格。

  

db_area:

id      name        distance

1       Raj           4    
2       Kalia         5    
3       Golu          10    
4       Pretty        15    
5       raghu         12    
6       Sallu         20    
7       Malli          25    
8       Nalia          1700   
9        Bull          7  
10      Kullu           3

我在解释下面的一些条件。

< 5 km->index 0
5-10 km ->index 1
10-20 km->index 2
> 20 km->index 3

此处用户有一个输入i.e-$dist=0 or 1 or 2 or 3。我需要按照$dist值获取数据。如果$dist value is 0 then the data will fetch from table where distance column value is less than 5$dist=1,那么data will fetch from table where distance is in bettween 5 and 10 KM等等。请帮助我。

2 个答案:

答案 0 :(得分:0)

您可以将switch case语句用作

$sql="select * from table Where 1=1 ";
switch ($dist) {
    case 0:
    $sql.=" and distance < 5";// for index 0
        break;
    case 1:
          $sql.=" and distance BETWEEN 5 and 10";
        break;
    case 2:
         $sql.=" and distance BETWEEN 10 and 20";
        break;
     case 3:
         $sql.=" and distance > 20";// greater then 20
        break;
    default:
         $sql=$sql;// default case
}

答案 1 :(得分:-1)

<?php
switch($dist) {
    case '0':
        $sql = "SELECT * FROM db_area WHERE distance < 5";
    break;
    case '1':
        $sql = "SELECT * FROM db_area WHERE distance BETWEEN 5 AND 10";
    break;
    case '2':
        $sql = "SELECT * FROM db_area WHERE distance BETWEEN 10 AND 20";
    break;
    case '3':
        $sql = "SELECT * FROM db_area WHERE distance > 20";
    break;
    default:
        $sql = "SELECT * FROM db_area";
}
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['name'];
    echo "<br />";
}
?>