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 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类