【问题标题】:PHP PDO - single query for multiple x fieldsPHP PDO - 多个 x 字段的单个查询
【发布时间】:2013-11-07 08:08:29
【问题描述】:

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

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

【问题讨论】:

  • 您的问题呢?做了哪些改变?它是一个单一的领域?相同类型的查询?
  • 我的查询是一个简单的更新。是相同类型的查询 (UPDATE)。
  • updatewhere 子句怎么样?还是对表中的所有行进行大规模更新?

标签: php mysql pdo mysqli


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

【讨论】:

    【解决方案2】:

    我不确定$_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));
    

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2012-06-24
      • 2020-11-04
      • 2017-08-13
      • 1970-01-01
      • 2020-06-27
      • 2017-02-01
      • 2016-11-23
      相关资源
      最近更新 更多