2013-04-08 154 views
10

我也碰到过这样的警告,我以前从未见过:PDO:无效的参数号:混合命名和位置参数

警告:PDOStatement对象::执行()[pdostatement.execute]:SQLSTATE [HY093 ]:无效参数号:混合命名和位置参数在...

参照以下PDO查询(已经简化为了便于阅读功能):

$offset = 0; 
$limit = 12; 
function retrieve_search_posts($searchfield, $offset, $limit){ 


     $where = array(); 

     $words = preg_split('/[\s]+/',$searchfield); 

     array_unshift($words, ''); 
     unset($words[0]); 

     $where_string = implode(" OR ", array_fill(0,count($words), "`post_title` LIKE ?")); 

     $query = " 
           SELECT p.post_id, post_year, post_desc, post_title, post_date, img_file_name, p.cat_id 
           FROM mjbox_posts p 
           JOIN mjbox_images i 
           ON  i.post_id = p.post_id 
             AND i.cat_id = p.cat_id 
             AND i.img_is_thumb = 1 
             AND post_active = 1 
           WHERE $where_string 
           ORDER BY post_date 
           LIMIT :offset, :limit 
           DESC"; 
     $stmt = $dbh->prepare($query); 

     foreach($words AS $index => $word){ 
      $stmt->bindValue($index, "%".$word."%", PDO::PARAM_STR); 
     } 
     $stmt->bindParam(':offset', $offset, PDO::PARAM_INT); 
     $stmt->bindParam(':limit', $limit, PDO::PARAM_INT); 
     $stmt->execute(); 

     $searcharray = $stmt->fetchAll(PDO::FETCH_ASSOC); 

     return $searcharray; 
    } 

函数和PDO查询工作正常,但不包含查询中包含的偏移量和限制变量。那么可能是什么原因导致了这种警告

感谢

+1

岂不是,你命名的混合参数(':offset',':limit')的事实与位置参数(' LIKE?')作为警告状态? – Wiseguy 2013-04-08 20:24:53

+0

@Wiseguy谢谢,我也知道他们现在叫什么:p – crm 2013-04-08 20:36:41

+1

@MarcB也许我错过了一些东西,但是你在哪里看到一个sql注入漏洞? – jeroen 2013-04-08 20:36:41

回答

8

变化

LIMIT :offset, :limit 

LIMIT ?, ? 

$stmt->bindParam(':offset', $offset, PDO::PARAM_INT); 
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT); 

到:

$stmt->bindValue($index+1, $offset, PDO::PARAM_INT); 
$stmt->bindValue($index+2, $limit, PDO::PARAM_INT); 
9

在where_string您使用?这是一个位置参数,并在你的极限和偏移您使用:被命名参数,导致该警告不要混合使用它们

+0

谢谢,你知道我怎么可以在where_String中使用命名参数而不是位置参数,反之亦然? – crm 2013-04-08 20:36:04

+0

@crm用':pattern1',':pattern2'或命名参数替换'?'实例,使用'?',并且它们将具有count + 1和count + 2的索引,其中count是正在检查的模式的数量。 – IMSoP 2013-04-08 20:47:32

+0

回答mekegi @mekegi谢谢 – Miguelo 2013-04-08 20:48:45