4

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());
  }
}
vcanales
  • 1,818
  • 16
  • 20
  • You are writing these queries in the array ahead of time, right? Why not make another array that contains the number of params? So, you just look up in the array based on which query you are trying to run. – gen_Eric Nov 05 '14 at 22:01
  • This is supposed to be somewhat dynamic, but a combination of this and the answer below should work. Thanks. – vcanales Nov 05 '14 at 22:03
  • 1
    alternative would be to specify `where 1:=id or 1=1`, basically subverting the parameter. – Marc B Nov 05 '14 at 22:07

1 Answers1

4

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
Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • Well I have no idea why I didn't think of that. Long day I guess. I'll accept the answer once 10 minutes have passed. Thanks. – vcanales Nov 05 '14 at 22:04