关于预备陈述

时间:2016-12-22 20:41:50

标签: php mysql

我在为WHERE子句的查询添加单引号时遇到问题,但有些人建议使用预编译语句进行数据库和简单的SQL查询我可以做到,但我不知道如何这可以在我的情况下完成,其中WHERE依赖于更改数组$ arr。所以,让我展示一些代码:

//The $arr can have different options (depends on user's choice) like below and more:
$arr = ["first_name"=>"a","second_name"=>"","third_name"=>"b"]; //user's input or
$arr = []; //user's input or
$arr = ["first_name"=>"a"]; //user's input or other 

$i = array("first"=>"f1","second"=>"f2","third"=>"f3"); //coded
$fName = "first"; //user's input

if (empty($arr)) {
  $where="";
} else {
  foreach($arr as $key => $value){
    $tmpkey = str_replace("_name", "", $key);
    if ($value=="") {
      $arr[$tmpkey]="0";
    } else {
      $newkey = $i[$tmpkey].".name";
      $arr[$newkey] = $value;
    }
    unset($arr[$key]);
  }    
  $where=preg_replace('/^(.*)$/e', ' "$1=\'". $arr["$1"]."\'" ',array_flip($arr));
  $where=implode(' AND ' , $where);
  $where = "WHERE ".$where;
}

$sql = "SELECT IFNULL({$i[$fName]}.name,'') AS {$fName}
          FROM tab1 p
            LEFT JOIN field1 f1
              ON p.first > 0 AND f1.id = p.first
            LEFT JOIN field2 f2
              ON p.second > 0 AND f2.id = p.second      
            LEFT JOIN field3 f3
              ON p.third > 0 AND f3.id = p.third
        {$where}
        GROUP BY {$fName}
        ORDER BY {$fName}
       ";

上面的问题是我在WHERE子句中遇到sql错误。有没有办法来解决这个问题?如何使用预处理语句完成此操作?

编辑:我用其他解决方案修复了WHERE子句,现在可以正常工作。

0 个答案:

没有答案