【发布时间】:2013-02-23 12:32:52
【问题描述】:
我有一个包含 3 个字词(搜索参数、邮政编码和活动类型)的搜索页面
我已经做了一个函数来编写sql:(这不是真正的函数,只是一个简化的函数)。您可以将它与要过滤的参数一起使用,也可以不使用参数来获取所有参数。
function get_items($search="",$postal_code="",$activity=""){
global $db; //this is the $db=new mysqli(...) in other include file
$where="";
if ($s!=""){
$s="%".$search."%";
$where=" AND ((item.name like '".$s."') OR (item.description like '".$s."'))";
}
if($postal_code!=""){
if (strlen($postal_code)==5){
$where=" AND (item.postal_code like '".$postal_code."')";
}
}
if($activity!=""){
if (m_is_integer($postal_code)){ //m_is_integer returns true if is an integer
$where=" AND (item.activity =".$activity.")";
}
}
$sql="select ....... from -..... where .....".$where." order by ......"
//yes, I know I don't need to prepare the query
$stmt=$db->prepare($sql);
$result=$stmt->execute();
$stmt->store_result();
$item_array=Array();
if (($result!=false) && ($stmt->num_rows>0)){
//do things and populate the array $item_array
}
$stmt->close();
return $item_array;
}
这个函数有效,sql 是正确组合的,你输入任何参数或不输入,并返回一个项目数组。
我想进行参数化查询,这是我的方法:
function get_items_parametrized($search="",$postal_code="",$activity=""){
global $db; //this is the $db=new mysqli(...) in other include file
$where="";
$bind_array=Array();
if ($s!=""){
$s="%".$search."%";
$where=" AND ((item.name like ?) OR (item.description like ?))";
$bii=Array("s",$s);
$bind_array[]=$bii;
$bii=Array("s",$s);
$bind_array[]=$bii;
}
if($postal_code!=""){
if (strlen($postal_code)==5){
$where=" AND (item.postal_code like ?)";
$bii=Array("s",$postal_code); //yes, is a string in the database
$bind_array[]=$bii;
}
}
if($activity!=""){
if (m_is_integer($postal_code)){ //m_is_integer returns true if is an integer
$where=" AND (item.activity = ?)";
$bii=Array("i",$activity);
$bind_array[]=$bii;
}
}
$sql="select ....... from -..... where .....".$where." order by ......"
$stmt=$db->prepare($sql);
//go to bind data to search
$bind_type="";
$bind_params=Array();
foreach($bind_array as $b){
$bind_type.=$b[0];
$bind_params[]=$b[1];
/* Approach 1: */
$stmt->bind_param($b[0],$b[1]);
}
/* Approach 2: */
$stmt->bind_param($bind_type,$bind_params);
$result=$stmt->execute();
$stmt->store_result();
$item_array=Array();
if (($result!=false) && ($stmt->num_rows>0)){
//do things and populate the array $item_array
}
$stmt->close();
return $item_array;
}
这个函数总是返回一个空的 $item_array Array () 而不是一个 Array(Array(),Array()) 如果我不绑定结果是可能的,执行不会返回任何结果。
我也尝试过:
/* attempt 3 */
$data=Array();
$data[0]="";
foreach($bind_array as $b){
$data[]=$b1;
$bind_type.=$b[0];
}
$data[0]=$bind_type;
组成一个类似 ('ssi',$s,$postal_code,$activity) 的数组来调用 call_user_func_array():
call_user_func_array(array(&$stmt, 'bind_param'), $data);
我也试试:
call_user_func_array(array($stmt, 'bind_param'), $data);
而且这种方法仍然没有返回任何数据。
我现在可以尝试什么使其适用于参数化查询?
欢迎任何帮助:D
【问题讨论】:
-
bind_param要求参数为引用,call_user_func_array不再传递引用。
标签: php mysqli sql-parametrized-query