dongleiwei2182 2015-08-30 13:22
浏览 157
已采纳

使用PDO构造条件SQL语句

what is the best way to construct an SQL statement with PDO when it depends on whether some PHP variable are set?

Here is an example;

$query="SELECT * FROM table ";

if($variable1 != "") {  $query = $query . "WHERE variable1 = :variable1";   }                   
if($variable2 != "") {  $query = $query . " AND variable2 = :variable2";    }                   

$query -> execute(array(':variable1' => $variable1, ':variable2' => $variable2));

I have a lot of these if statements and when binding the variables to the query I don't want to go through all these if statements again.

Is there an easier way to construct an SQL statement with such if/else conditions?

  • 写回答

1条回答 默认 最新

  • dsgs8208 2015-08-30 13:28
    关注

    I would use an array to contain each part of the where... as a match occurs, add the resulting statement to the array. After all are evaluated, implode, separating with " AND " and concatenate onto $query.

    $arrWhere = array();
    $assWhere = array();
    
    if($variable1 != "") {
        $arrWhere[] = "variable1 = :variable1";
        $assWhere[":variable1"] = $variable1;
    }
    if($variable2 != "") {
        $arrWhere[] = "variable2 = :variable2";
        $assWhere[":variable2"] = $variable2;
    }
    if($variable3 != "") {
        $arrWhere[] = "variable3 = :variable3";
        $assWhere[":variable3"] = $variable3;
    }
    
    $query="SELECT * FROM table WHERE " . implode ( " AND " , $arrWhere );
    
    $query -> execute($assWhere);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退