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

帅比萌擦擦* 提交于 2019-12-06 13:01:10

问题


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?


回答1:


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);



回答2:


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.




回答3:


$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);


来源:https://stackoverflow.com/questions/583592/how-do-i-build-a-parameterized-pdo-statement-in-php-for-a-dynamic-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!