Is it possible to count the number of parameters in a prepared PDO statement?

I need to process multiple requests using a loop and all requests are the same except those that don't use the parameter that others do:

$queries = array(
  'query1' = "SELECT * FROM table_1 WHERE id=:id",
  'query2' = "SELECT * FROM table_2 WHERE id=:id",
  'query3' = "SELECT * FROM table_3"
);

$params = array(':id',1);

foreach($queries as $q) {
  $st = $pdo->prepare($q);
  if($st->execute($params)) {
    // do stuff with results
  } else {
    echo json_encode($st->errorInfo());
  }
}

      

The problem is that $ st-> execute ($ params) won't work on a request without any parameters, so I would like to know if the request can be parsed before submitting it.

This is bogus code and should work regardless of the structure of the request if there is one parameter (: id) or none.

UPDATE SOLVED:

How I applied the solution given by @ Jonast92:

foreach($queries as $q) {
  $st = $pdo->prepare($q);
  if($st->execute(substr_count($q,":") > 0 ? $params : null)) {
    // do stuff with results
  } else {
    echo json_encode($st->errorInfo());
  }
}

      

+3


source to share


1 answer


You can use substr_count to count a number :

indicating the number of arguments to be executed in the prepared statement.



$itemInArray = "SELECT * FROM table_1 WHERE id=:id";
$count = substr_count($itemInArray, ':'); // 1

      

+3


source







All Articles