0

I am going to ask 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?

Community
  • 1
  • 1
genesis
  • 50,477
  • 20
  • 96
  • 125

4 Answers4

4
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

plague
  • 1,908
  • 11
  • 11
  • this is what I was looking exactly. – genesis Jul 24 '11 at 00:02
  • +1, this is much cleaner than hacking together a string and then trimming it. However, it can still be improved. `file()` returns an array already, so you can just `echo 'INSERT INTO TABLE VALUES (' . join(') (', file('file.txt')) . ');'` (assuming that you know there is at least one line in the file). – El Yobo Jul 24 '11 at 00:16
3
$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);
zerkms
  • 249,484
  • 69
  • 436
  • 539
3
foreach(file('file.txt') as $line){
    $query .= "('".$line."'),";
}
echo "INSERT INTO table VALUES " . rtrim($query,',');
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • well, I did use this too, I forgot it, though :) Thanks for reminiding it ! +1 – genesis Jul 23 '11 at 23:52
  • I prefer this one as it is much more readable and it will be easier to work out what is happening when you look at it again in 6 months time. Clever code is good, readable code is better and clever, readable code is best :) . I've had enough of non-obvious code, especially my own! Anyway, +1 – vascowhite Jul 24 '11 at 00:00
  • I disagree, the implode approach is clearer to read, more elegant and more efficient. – El Yobo Jul 24 '11 at 00:14
  • To each his own, I suppose. I actually prefer zerkms to my own haha. Wish I'd thought of it myself! :) – AlienWebguy Jul 24 '11 at 00:45
1

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

Bryan Alves
  • 619
  • 4
  • 7