drby30217 2013-12-28 11:56
浏览 44
已采纳

处理PHP SQL查询中的可选搜索参数

I'm querying my SQL database in a PHP file from up to three optional search fields (passed through by jQuery). Any one, two or three of these fields can be used at any time to make the query as expansive or as narrow as the user likes. If nothing is in a search field nothing will be returned.

I've written the code so far to handle very basic one search queries and have just begun to add in the multiple parameters - this is where it's starting to get tricky. I can query two fields together without too much bother but adding a third LOCATION parameter is beginning to take up too much code for all of the querying possibilities a user might make.

Here's how my PHP file is set up for two parameters:

if (!empty($_POST['title']) && (!empty($_POST['name']))) 
{
    require '../db/connect.php';
    $sql = "SELECT 
               ....
            FROM 
               ....
            WHERE 
                `table 3`.`TRACKTITLE` = '" . mysql_real_escape_string(trim($_POST['title'])) . "' AND `table 3`.`ARTIST` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'";              
}   


if (!empty($_POST['name']))
 {
    require '../db/connect.php';
    $sql = "SELECT 
              ...
            FROM 
              ...
            WHERE 
              `table 3`.`ARTIST` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'";

}   

if (!empty($_POST['title'])) {
    require '../db/connect.php';
    $sql = "SELECT 
            ...
            FROM 
            ...
            WHERE 
            `table 3`.`TRACKTITLE` = '" . mysql_real_escape_string(trim($_POST['title'])) . "'";
}   

$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;

Which is the simplest way to build a query with multiple optional parameters in PHP, accounting for any additional parameters that might be added on at a later date? I've read up on isnull values but do they perform a similar function to !emtpy?

  • 写回答

1条回答 默认 最新

  • dsgdfg30210 2013-12-28 12:04
    关注

    Do something along this line:

    $whereclauses = array();
    $subsets = false;
    
    // for every field
    if(!empty($_POST['name']))
      {
      $subsets = true;
      $whereclauses[] = " artist = ". mysql_real_escape_string(trim($_POST['name']));
      }
    
    if($subsets)
      {
      $whereclauses = implode(", ". $whereclauses);
      }
    else
      {
      $whereclauses ="";
      }
    
    // now build your query
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示