PDO: Invalid parameter number: mixed named and positional parameters

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

I have come across this warning I've not seen before:

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters in...

Referring to the following PDO query (have simplified the function for ease of reading):

$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;     }

The function and PDO query works fine without the offset and limit variables included in the query. So what might be causing this warning?

Thanks

回答1:

Change

LIMIT :offset, :limit

to

LIMIT ?, ?

and

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

to:

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


回答2:

in your where_string you use ? that is a positional parameter and in your limit and offset you use : that is a named parameter that is causing the warning don't mix them



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!