PHP PDO - 多个 x 字段的单个查询


PHP PDO - single query for multiple x fields

我有三个字段,我只需要更新已填写的字段。可能的解决方案如下:

<?php
if(trim($_POST['field_1'])!='')
   // query for update field 1
if(trim($_POST['field_2'])!='')
   // query for update field 2 
if(trim($_POST['field_3'])!='')
   // query for update field 3
?>

但这不是最好的优化,你能给我一个例子,说明如何使用 mysqli(带绑定)或 PDO 进行单个查询吗?

您可以动态构建查询。

$fields = array();
foreach($_POST as $key => $value) {
    // Only grab whitelisted fields
    if (in_array($key, array('field_1', 'field_2', 'field_3'))) {
        if (!empty(trim($value))) {
            // Using the keys from $_POST assumes they are named after their database counterparts
            $fields[$key] = trim($value);
         }
    }
}
// Grab the keys (fieldnames) so we can use them to build the query
$keys = array_keys($fields);
$sqlFieldsPart = implode(', ', array_map(function($field) {
    return $field . '= :' . $field;
}, $keys));
$sql = sprintf('UPDATE tablename SET %s WHERE somefield=:somefield', $sqlFieldsPart);
$dbh = new PDO('mysql:hostname=localhost;dbname=yourdb', 'username', 'password');
$stmt = $dbh->prepare($sql);
// Modify keys on $fields
$data = array();
foreach ($fields as $key => $value) {
     // Note the colon before the key variable, this is necessary
     // It links to the placeholders in the query
     $data[':' . $key] = $value;
}
// Set the value for the where clause
$data[':somefield'] = 'somevalue';
// Execute the statement, passing the data to the execute function
$stmt->execute($data);

此代码假定您的 html 字段以其数据库对应项命名。如果不是这种情况,您可以为每个字段硬编码第一个 foreach 循环中的内容,或者进行某种字段映射。

我不确定$_POST是否包含相关字段或更多字段,所以我假设您会找到一种方法将它们隔离在$tmp数组中并改用它。

我还假设您已经使用 PDO 与数据库建立了连接,并将其存储在 $db 中。

最后,您的行过滤器(where子句)已经在 $rowfilter 中构建为字符串。

// trim all values
array_map('trim',$tmp);
// eliminate empty string values
$tmp=array_filter($tmp,function($el){return $el!='';});
// build the query string
$fields=array_map(function($el){$el="`$el`=?";},array_keys($tmp));
$fldstr=implode(',',$fields);
$sql="UPDATE `mytable` SET $fldstr WHERE $rowfilter";
// prepare and execute
$stmt = $db->prepare($sql);
$stmt->execute(array_values($tmp));