通过选择选项标记从数据库中获取数据,以便在选择所有'数据库应该选择' *'

时间:2017-08-06 11:36:48

标签: php html mysql

我正在尝试使用选择标记制作一个搜索框,这样如果我选择全部'在select option标签中,应该获取该列的每个数据。

以下是我的php代码。感谢

if(isset($_POST['submit'])) {
    $area = $_POST['city'];
    if(isset($_POST['work']!== 'all')) 
        {$work = $_POST['work']; } 
    else {$work = '*';} ;

    $sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."' AND `work`='".$work."'" ;  
  $res2 = mysqli_query($con,$sel2);

2 个答案:

答案 0 :(得分:0)

由于您希望在work等于all时获取任何和所有与工作相关的数据,因此您不必在SQL查询中明确提及。仅在您要获取特定工作相关数据时才提及 。所以你的代码应该是这样的:

if(isset($_POST['submit'])) {
    $area = $_POST['city']; 
    $sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."'";
    if(isset($_POST['work']) && $_POST['work'] !== 'all') 
        $sel2 .= " AND `work`='".$_POST['work']."'";
    $res2 = mysqli_query($con,$sel2);

旁注:了解prepared statement因为您的查询现在容易受到SQL注入攻击。另请参阅how you can prevent SQL injection in PHP

答案 1 :(得分:0)

设置像这样的变量

if(isset($_POST['submit'])) {
    $area = $_POST['city'];
    if(isset($_POST['work']!== 'all'))
$data=addslashes($_POST['work']); 
        {$work = "AND `work`='".$data."'";
} 
    else {$work = "";
}
///your query should be like this
$sel2 = "SELECT * FROM `userdata` WHERE `area`='".$area."' ".$work."";  
//////so if work is not specified then you don't need to select column WORK in the query. So it works as select * from userdata where area='".$area."';";

  $res2 = mysqli_query($con,$sel2);