In general, I have been working with PDO recently and have already failed to understand how the error is:

$stmt = $pdo->prepare("(SELECT COUNT(goods_id) as count_rows FROM goods WHERE goods_brandid = :category AND visible='1') UNION (SELECT COUNT(goods_id) as count_rows FROM goods WHERE goods_brandid IN (SELECT brand_id FROM brands WHERE parent_id = :category) AND visible='1')"); $stmt->execute(array("category" => $category)); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ if($row['count_rows']) $count_rows = $row['count_rows']; } return $count_rows; 

And here is the error:

 Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number in D:\OpenServer\domains\InterMag.ru\model\model.php:138 Stack trace: #0 D:\OpenServer\domains\InterMag.ru\model\model.php(138): PDOStatement->execute(Array) #1 D:\OpenServer\domains\InterMag.ru\controller\controller.php(140): count_rows(Object(PDO), 5) #2 D:\OpenServer\domains\InterMag.ru\index.php(10): require_once('D:\\OpenServer\\d...') #3 {main} thrown in D:\OpenServer\domains\InterMag.ru\model\model.php on line 138 

Tell me where is the error ??

2 answers 2

To fix this error in this particular case, there are two ways:

  1. Enable emulation mode
  2. Pass the variable to the request twice, i.e. do something like

     $stmt->execute(array("category1" => $category,"category2" => $category)); 

    by changing the placeholders in the query accordingly.

However, there is not the slightest sense to carry out these two requests through the union, and the easiest way is to execute them separately.

  • Colon when canceled? - Visman
  • they were never imputed - Ipatiev
  • And the manuals lie? php.net/manual/ru/pdostatement.execute.php - Visman
  • Well, in general, it seems clear that in PDO you cannot use one placeholder twice in one request - Moonwolf45
  • @ Moonwolf45 is actually possible, which is what is written in my answer. - Ipatiev

Correct the key in the array that you pass to execute ();

 $stmt->execute(array(":category" => $category));