2013-02-23 2 views
0

작동하지 않는에서 매개 변수화 만약 내가 3 개 학기 (월로 매개 변수, 우편 번호, 및 활동의 유형)구성 MySQL의 쿼리 작업을하지만, mysqli는

내가 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 배열 (반환)하지 배열 (배열(), 배열()) 그 결과를 바인딩하지 않으면 실행 가능합니다. 실행 결과가 반환되지 않습니다.

/* attempt 3 */ 
$data=Array(); 
$data[0]=""; 
foreach($bind_array as $b){ 
    $data[]=$b1; 
    $bind_type.=$b[0]; 
} 
$data[0]=$bind_type; 

가 ('SSI', $ s에, $의 우편 _ 번호, $ 활동)과 같은 배열을 작성하려면) (call_user_func_array하는 전화 :

call_user_func_array(array(&$stmt, 'bind_param'), $data); 

는 또한하려고 노력 나는 또한 시도 :

call_user_func_array(array($stmt, 'bind_param'), $data); 

그리고이 방법은 여전히 ​​데이터를 반환합니다.

매개 변수화 된 쿼리로 작동 시키려면 어떻게해야합니까?

어떤 도움을 환영합니다 : D

+0

'bind_param'는 참조로 매개 변수를 필요로'call_user_func_array' 더 이상 참조를 전달하지 않습니다. – Barmar

답변

1

대답은 간단하다 : 는 준비된 명령문과 mysqli에게를 사용하지 마십시오.
준비된 문과 함께 사용할 수 없습니다.
대신 PDO을 사용하십시오.
은 대답입니다. Mysqli가 문제이고 해결해야합니다.

PDO를 사용하면 코드가 3 배 짧아지고 작동합니다.

mysqli를 고수하고 싶다면 다른 방법은 준비된 문장을 없애고 자신의 자리 표시자를 구현하는 것입니다.하지만 약간의 지식이 필요합니다. 그러나, 당신은 쉽게 조건부 쿼리를 작성하게됩니다 :

$w = array(); 
$where = ''; 
if ($one) $w[] = $db->parse("one = ?s",$one); 
if ($two) $w[] = $db->parse("two IN (?a)",$two); 
if ($tre) $w[] = $db->parse("tre <= ?i",$tre); 
if (count($w)) $where = "WHERE ".implode(' AND ',$w); 
$data = $db->getArr("SELECT * FROM table ?p LIMIT ?i,?i",$where, $start,$per_page); 
+0

에 대한 '나는 시간이있다'해결책을 시도 하겠지만, 이제는 pdo를 사용할 수 없으며, 서버에서 사용할 수 없으며 모든 응용 프로그램은 mysqli를 사용하고있다 (하나의 함수에 대해 하나의 연결 문자열을 만들지는 않을 것이다) . 감사합니다 –

+0

[safemysql] (https://github.com/colshrapnel/safemysql/blob/master/safemysql.class.php)을 사용할 수 있습니다. 그것은 당신이 조건부 질의를 만들게하고 mysqli를 사용한다. 나는 내 대답에 대한 모범이 될 것이다. –

+0

시도 할 것이지만 왜 매개 변수가있는 쿼리가 작동하지 않는지 이해할 수 없습니다. –