Friday, April 8, 2011

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

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?

From stackoverflow
  • 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.

  • 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);
    
    Barry : This looks about right. I will test it out today, thanks!
    DisgruntledGoat : It should also be noted that `$TempSQL = $TempSQL . 'something'` can be shortened to `$TempSQL .= 'something'`

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.