简体   繁体   中英

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

When I need to loop over something while generating a query from each element, I would use something like

$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

Would there be an alternative? I don't mind performance too much (knowing the length of the array is not too big), just something that looks nicer.

Using a prepared statement:

$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']));
}

More examples: http://www.php.net/manual/en/pdo.prepare.php

A slight improvement to get rid of last part (removing latest comma). You can first create an array of values, then use implode function like:

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

I like using array_walk and implode for things like this:

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

The result looks like this:

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

Maybe not much cleaner, but at least it gets rid of the for loop :-)

You could use implode() with array_map() :

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

Demo

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

Thats part of the database class I have written... I pass in the arrValues ('ColumnName'=>'Value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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