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 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数