How do I build a parameterized PDO statement in PHP for a dynamic query?

By : Barry
Source: Stackoverflow.com
Question!

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?

By : Barry


Answers
$TempSQL = 'SELECT field1, field2, field3 FROM table';
$cond = array();
$params = array();
if (!empty($val1)) {
    $cond[] = "field1 = ?";
    $params[] = $val1;
}
if (!empty($val2)) {
    $cond[] = "field2 = ?";
    $params[] = $val2;
}
if (!empty($val3)) {
    $cond[] = "field3 = ?";
    $params[] = $val3;
}
if (count($cond)) {
    $TempSQL .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $pdo->prepare($TempSQL);
$stmt->execute($params);


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);
By : Zoredache


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.

By : Nerdling


This video can help you solving your question :)
By: admin