views:

419

answers:

2

Apologies if this has been asked already. I've seen answers regarding static SQLs, but in this case I'd like to use PDO->prepare() for a query string that is built dynamically at runtime.

Breaking down into a simple example:

$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";

if ($numberParams == 1) {
    $TempSQL = $TempSQL . " field1 = '$val1' ";
} else {
    $TempSQL = $TempSQL . " field2 = '$val2' ";
    $TempSQL = $TempSQL . " AND field3 = '$val3' ";
}

db->query($TempSQL);

How do I rewrite this as a db->prepare()?

Should I build the statement->execute(array(':param' => $var))) on the fly as well?

Is there a better / neater way?

A: 

Based on your example, a neater way would be a loop instead of switching.

db->prepare() allows you to replace patterns (on php.net, the example is putting a colon in front of the field name) using bindParam() or an array on the PDOStatement->exec(). You can use the ? from examples 3 and 4 instead of naming the field values.

It still requires that all the fields be known for the SQL statement.

Nerdling
+1  A: 

Perhaps something like this. (untested)

$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
$args=array();

if ($numberParams == 1) {
    $TempSQL = $TempSQL . " field1 = :val1"
    $args[':val1']=$val1;
} else {
    $TempSQL = $TempSQL . " field2 = :val2 and field3 = :val3";
    $args[':val2']=$val2;
    $args[':val3']=$val3;
}

$stmt=$db->prepare($TempSQL);
$stmt->execute($args);
Zoredache
This looks about right. I will test it out today, thanks!
Barry
It should also be noted that `$TempSQL = $TempSQL . 'something'` can be shortened to `$TempSQL .= 'something'`
DisgruntledGoat