开发者

Is there more elegant way to implode data to query?

I am going to 开发者_如何学Cask because of this answer.

My code looks like

<?php
$lines = file('file.txt');
$count = count($lines);
$i = 0;
$query = "INSERT INTO table VALUES ";
foreach($lines as $line){
    $i++;
    if ($count == $i) {
        $query .= "('".$line."')";
    }
    else{
        $query .= "('".$line."'),";
    }
}
echo $query;

is there more elegant way to do this/function in php?


foreach ( $lines AS $line )  
{  
  $query[] = "($line)";  
}  

echo  "INSERT INTO table VALUES " . implode(",",$query);

is how to do it with implode but i think AlienWebguy's is better


foreach(file('file.txt') as $line){
    $query .= "('".$line."'),";
}
echo "INSERT INTO table VALUES " . rtrim($query,',');


$query = 'INSERT INTO table VALUES ';
$query .= "('" . implode("'), ('", $lines) . "')";

UPD:

For 2 fields it could look like (I suppose you use php5+):

$query = 'INSERT INTO table VALUES ';

$lines = array(array(1,2), array(3,4));
$query .= "('" . implode("'), ('", array_map(function($i) { return "'" . implode("', '", $i) . "'"; }, $lines)) . "')";

var_dump($query);


LOAD DATA INFILE is better suited for this specific task: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜