0
$lines = file('array2.txt');
    foreach($lines as $line)
    {
        mysql_query("INSERT INTO test (Tweet, Date) VALUES ('$line', '22')");
    } 

Hi All,

I am trying to use the code above to use the file() function to add lines from a text file into an array, so I can then place it in a mysql database. The file I am using contains a 100 lines, but using the function above I end up with over 116,000. Does anyone known how what is causing this? Thank you in advance.

7
  • 1
    PSA: The mysql_* functions are deprecated in PHP 5.5. It is not recommended for writing new code as it will prevent you from upgrading in the future. Instead, use either MySQLi or PDO and be a better PHP Developer. Commented Aug 26, 2013 at 13:14
  • 3
    Show a few lines of the file data. Commented Aug 26, 2013 at 13:14
  • 1
    any chance that you file might contain empty lines? Commented Aug 26, 2013 at 13:15
  • #PowerdbyFord #Ford #Highboy t.co/pMqX RT @_LiftedTrucks_: #Ford t.co/cnrr RT @_LiftedTrucks_: #Ford http://t.co/cnrr RT @_LiftedTrucks_: #Ford http://t.co/cnrr ‚Äö√Ñ√∫@_LiftedTrucks_: #Ford http://t.co/iYUIAZp7hb‚ "@_LiftedTrucks_: #Ford http://t.co/F4FRMbMqC4" I want this @baile This is a few lines from the file. Commented Aug 26, 2013 at 13:18
  • 1
    Please put array2.txt on PasteBin... Commented Aug 26, 2013 at 13:20

2 Answers 2

1

Maybe try this way. You will read till file end line.

$file = fopen("file.txt", "r");
while (!feof($file)) {
    $line = fgets($file);
    // Code where you make DB INSERT
}
fclose($file);

For me this works, and I don't get any other records, only those 10 which i wrote in.

Sign up to request clarification or add additional context in comments.

Comments

0

try this:

<?php
$lines = file('array2.txt');
foreach($lines as $line)
{
  if(!empty($line)){
    $values[]= "('".mysql_real_escape_string($line)."', '22')";
  }
}
$query = "INSERT INTO test (Tweet, Date) VALUES ".implode(",",$values);
$result = mysql_query($query) or die(mysql_error());
?>

Note: I suggest to use mysqli or PDO because mysql function depreciated.

4 Comments

Hi there, I just tried your code, and I get the following error "MySQL server has gone away"
echo $query; before $result and see how the query printed
@user2694239 Sounds like you've exceeded the max_allowed_packet setting though that can be adjusted.
Without mysql_real_escape_string this answer presumes a lot about the nature of the data being imported.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.