1

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

<?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 进行单个查询吗?

4

2 回答 2

1

您可以动态构建查询。

$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 循环中为每个字段硬编码或进行某种字段映射。

于 2013-11-07T09:01:27.333 回答
1

我不确定是否$_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));
于 2013-11-07T09:20:06.460 回答