繁体   English   中英

PHP中更优雅的方式从数组元素生成查询

[英]More elegant way in PHP to generate a query from array elements

当我需要从每个元素生成查询时遍历某些内容时,我会使用类似

$queryStr = "INSERT INTO tableName (x,y) VALUES ";
for ($i = 0 ; $i < $len ; $i++)
{
   $queryStr .= "( ".$thing[$i]['x'].", ".$thing[$i]['b']."), ";
}
//extra code to remove the last  comma from string

会有其他选择吗? 我不太在意性能(知道数组的长度不是太大),只是看起来更好。

使用准备好的语句:

$sql = 'INSERT INTO tableName (x, y) VALUES (:x, :y)';
$sth = $dbh->prepare($sql);
for ($i = 0 ; $i < $len ; $i++)
{
  $sth->execute(array(
    ':x' => $thing[$i]['x'], 
    ':y' => $thing[$i]['b']));
}

更多示例: http : //www.php.net/manual/zh/pdo.prepare.php

略有改善,以摆脱最后一部分(删除最新的逗号)。 您可以先创建一个值数组,然后使用爆破功能,例如:

$queryStr = "INSERT INTO tableName (x,y) VALUES ";
for ($i = 0 ; $i < $len ; $i++)
{
  $values[] = "( ".$thing[$i]['x'].", ".$thing[$i]['b'].")";
}
$queryStr .= implode(',', $values);

我喜欢使用array_walk并内implode的事情:

$values = array(
    array(1, 2, 3),
    array(4, 5, 6),
    . . .
);

// an array to hold the values to insert
$query = array();

// walk the values and build the query array
array_walk($values, function($v) use(&$query) {
    $query[] = "(" . implode(", ", $v) . ")";
});

// dump the output
echo implode(", ", $query);

结果看起来像这样:

(1, 2, 3), (4, 5, 6), ...

也许还不算干净,但是至少它摆脱了for循环:-)

您可以将implode()array_map()

implode(', ', array_map(function($v) { return '(' . $v['x'] . ', ' . $v['b'] . ')'; }, $things));

演示版

    $strCols =  '`'.implode('`, `',array_keys($arrValues)).'`'; //Sets the array keys passed in $arrValues up as column names
    if ($bolEscape){ //Checks if $bolEscape is true
            $arrValues = $this->escape($arrValues); //Calls the escape function
            $strValues = '"'.implode('","',array_values($arrValues)).'"'; //Sets the array values passed in $arrValues up as data for the columns
        }else{
            $strValues = '"'.implode('","',array_values($arrValues)).'"'; //Sets the array values passed in $arrValues up as data for the columns WITHOUT escaping
        }
            //Creates the SQL statement for the query
        $strSQL = 'INSERT INTO `' . $strTable . '` (' . $strCols . ') VALUES (' . $strValues . ')';

那就是我编写的数据库类的一部分...我传入了arrValues('ColumnName'=>'Value')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM