douyue1998 2016-01-14 22:58
浏览 45
已采纳

动态搜索PHP MYSQL PDO

I have a form with 3 select boxes: age,room,type.

<form action="results.php" method="get">
<div class="form-group">
<select name="age">
     <option value>Any</option>
     <option value="1">15</option>
     <option value="2">25</option>
     <option value="3">30</option>
     <option value="4">40</option>
   </select>
</div>
<div class="form-group">
<select name="room">
     <option value>Any</option>
     <option value="1">1</option>
     <option value="2">2</option>
   </select>
</div>
<div class="form-group">
<select name="type">
     <option value>Any</option>
     <option value="1">Personal</option>
     <option value="2">Business</option>
   </select>
</div>
</form> 

What i am trying to do with PDO is to make a small search. If all variables are empty then my condition is:

$search = $db->query("SELECT * FROM table");

If 1 of them (as example the age) is not empty then i have:

 if(!empty($_GET['age'])){
$age = $_GET['age'];
$search = $db->query("SELECT * FROM table WHERE age = '$age'");
}

Now, if 2 of them are npt empty i have:

if(!empty($_GET['age']) && !empty($GET['room'])){
    $age = $_GET['age'];
$room = $_GET['room'];
    $search = $db->query("SELECT * FROM table WHERE age = '$age' AND room = '$room'");
    }

In order to avoid all possible search combinations, how can i make a search with the term if is not empty. I had made one in the past:

if(!empty($age)){
$where = "WHERE age = '$age'";
}

if(!empty($room)){
$where .= "and room = '$room'";
}

$query = "SELECT * FROM table $where";

How can i make it happen with PDO?? :/

  • 写回答

2条回答 默认 最新

  • dreamfly2016 2016-01-14 23:13
    关注

    I'd do something like this:

    $param = array();
    $query = 'SELECT ... FROM t WHERE 1=1';
    
    if(!empty($_GET['age'])){
      $param['age'] = $_GET['age'];
      $query .= ' AND t.age = :age';
    }
    
    if(!empty($_GET['room'])){
      $param['room'] = $_GET['room'];
      $query .= ' AND t.room = :room';
    }
    
    if(!empty($_GET['type'])){
      $param['type'] = $_GET['type'];
      $query .= ' AND t.type = :type';
    }
    
    $dbh->prepare($query)->execute($param);
    

    You might want to separate out the prepare and the execute. Check the return from the prepare before you try calling execute. Or, configure PDO can throw an exception when an error occurs, e.g.

     $dbh->setAttribute(PDO::ERRMODE_EXCEPTION);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100