tags:

views:

65

answers:

3

I'm trying to load data from a few hundred text files into a database.

I believe MYSQL is exiting out of the loop without inserting all the rows.

Can anyone suggest how to insert blocks of 1000 rows to the end of data, with PHP code?

$filenames_array = array();

foreach($filenames_array as $filename)
{

        $file_array  = file($filename);
        $file_value  = $file_array[0];
        $new_array  = explode(",", $file_value);
        $length         = count($new_array);


        for($i = 0; $i < $length; $i++)
        {

        $sql = "INSERT INTO `names`
         (`id`, `name`)  

         VALUES 
         ('',
         '" . $new_array[$i] . "'
         )";

        $result = mysql_query($sql) or die(mysql_error());
        echo $i . 'Row Inserted<br />';
        }

    }
A: 

you're probably trying to run too many INSERT statements in a single query.

look into PDO and prepared statements or use SQL syntax like this:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Stephen
if he's dealing with a few hundred text files, I don't think the multiple insert syntax would be a viable solution?
jaywon
he's not really sending out many inserts in a single query - always just one at a time
michaelk
Inserting multiple rows with one query is faster than with multiple queries so if his script times out rewriting it to insert 1000 rows in one query might help.
Kamil Szot
A: 

Is it possible that one of the entries you're trying to insert contains a single quote '? In this case, an error would occur and the the loop wouldn't finish.

You should always escape the values you insert into the database with mysql_real_escape_string to prevent problems like that, and to make sure you're not vulnerable to sql injection.

    $sql = "INSERT INTO `names`
            (`id`, `name`)   

            VALUES 
            ('',
            '" . mysql_real_escape_string($new_array[$i]) . "'
            )";
michaelk
The data does not contain single quotes. I think this is a MYSQL issue.
rrrfusco
A: 

Why not combine every txt file into one big text file, and read it line by line? See the examples here http://php.net/manual/en/function.fgets.php

Mainly:

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>
darkAsPitch
I have several hundred textfiles. Copy and Pasting all the information defeats the purpose of writing this code. MYSQL exits after around 1100 row inserts also. I need to insert around 6000 rows.
rrrfusco
By combining everything into a text file, I didn't mean copy and paste. Maybe you could read a list of all files into an array, copy the contents of each one using file_get_contents and file_put_contents, and have it all done automatically! :)
darkAsPitch