vcanales
vcanales

Reputation: 1828

Is it possible to count number of parameters on a PDO Prepared Statement?

I have to process a few queries using a loop and all queries are the same, except for one which doesn't use the parameter the 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 here is that $st->execute($params) will not work on the query with no parameters defined, which is why I would like to know if it is possible to analyze the query before sending it.

This is fake code, and it should work regardless of the query structure as long as 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());
  }
}

Upvotes: 4

Views: 629

Answers (1)

Jonast92
Jonast92

Reputation: 4967

You can use substr_count to count the number of : occurring, indicating the number of arguments to be executed onto the prepared statement.

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

Upvotes: 4

Related Questions