PHP nested problems while querying

I am working on a project. I need to query a DB and write the result to a csv file. The result is going to be over 15,000 entries, (thats what the user wants). I am breaking up the results using the LIMIT because if I don't the DB will time out. I divide the query in what I call total_pages. Here is my code.

The big for loop, loops 19 times. The problems is that the code will go through the nested loop one time ( only 500 entries) then It does not go back in. I tried using null on the $results but no luck. Please help.

// using this for my LIMIT
$start_from = 0; 

$sql = "select * from someplace where gender = '".$gender."'";

$rs_result = mysql_query($sql);

$total_records =  mysql_num_rows($rs_result);

$total_pages = ceil($total_records / 500);

// open a file

//write x in file

file = fopen("./DataFile/gdownload.csv","w");

//write header to the file

$x = "Last Name,First Name,Primary_Name, ........ etc...... \n";

fwrite($file, $x);

for($count = 0; $count <= $total_pages; $count++)

    $query = "SELECT * 
             FROM ptable
            JOIN person_name ON ptable.Primary_Name = person_name.Primary_Name
            WHERE gender = '$gender'
            ORDER BY person_name.Lname ASC
            LIMIT ".$start_from.", 500";

    $result = mysql_query($query) or die(mysql_error());

    $num_row = mysql_num_rows($result);

    //print tables in rows

    while($row = mysql_fetch_array($result))
                fwrite($file, $x);
        }// end nested while

   }// end for loop


It could be a problem with your LIMIT condition. What you have seems OK to me but the fact that the rows are only being written on the first pass through makes me think $result is empty after the first pass.

Try changing

LIMIT ".$start_from.", 500";


LIMIT 500 OFFSET ".$start_from;

Also make sure the query actually returns more than 500 results.

On a different note, it's odd that the request would timeout on just 15,000 records.

Need Your Help

How do I get the data from a visual studio text box into a database?

c# sql database

I can't seem to get the info inserted into the text field to go to the database. Here's what I have so far.

How to capitalize the first character of each word in a string

java string uppercase lowercase capitalization

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?