Question

I'm trying to process a for loop within a for loop, and just a little wary of the syntax... Will this work? Essentially, I want to run code for every 1,000 records while the count is equal to or less than the $count... Will the syntax below work, or is there a better way?

for($x = 0; $x <= 700000; $x++) {
  for($i = 0; $i <= 1000; $i++) {
     //run the code
  }
} 
Was it helpful?

Solution

The syntax you have will work, but I don't think it's going to do exactly what you want. Right now, it's going to do the outer loop 700,001 times, and for every single one of those 700,001 times, it's going to do the inner loop.

That means, in total, the inner loop is going to run 700,001 x 1001 = about 700.7 million times.

If this isn't what you want, can you give a bit more information? I can't really work out what "I want to run code for every 1,000 records while the count is equal to or less than the $count" means. I don't see any variable named $count at all.

OTHER TIPS

Well, essentially, I'm reading in a text file and inserting each of the lines into a db. I did originally try while(!feof($f)) [where $f = filename], but it keeps complaining of a broken pipe. I thought this would be another way to go

$f should be file-handle returned by fopen(), not a filename.

$file_handle = fopen($filename, 'r');

while(!feof($file_handle)) {
    $line = fgets($file_handle);

    $line = trim($line); // remove space chars at beginning and end

    if(!$line) continue; // we don't need empty lines

    mysql_query('INSERT INTO table (column) '
               .'VALUES ("'.mysql_real_escape_string($line).'")');
}

Read through the documentation at php.net for fopen(), fgets(). You might also need explode() if you need to split your string.

If your file isn't big, you might want to read it into an array at once like this:

$filelines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($filelines as $line) {
   do_stuff_with($line);
}

Hmm. Ok... Well, essentially, I'm reading in a text file and inserting each of the lines into a db. I did originally try while(!feof($f)) [where $f = filename], but it keeps complaining of a broken pipe. I thought this would be another way to go..

To read a text file line by line I usually:

$file = file("path to file")
foreach($file as $line){
 //insert $line into db
}

Strictly answering the question, you'd want something more like this:

// $x would be 0, then 1000, then 2000, then 3000
for($x = 0; $x < 700000; $x += 1000) {
  // $i would be $x through $x + 999
  for($i = $x; $i < $x + 1000; $i++) {
     //run the code
  }
}

However, you should really consider one of the other methods for importing files to a database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top