I’m trying to get a script to work wherein certain selected records (depending on user input) are selected and then exported to a CSV file. I’ve tried all sorts of methods to do this; thus far this is the most successful I could find (actually from some code I did a few years ago), but it only returns the first row over and over again until the rows run out (you can see my sawdust-in-the-transmission method I used to tell PHP to keep getting rows until the result is exhausted). My questions: There is probably an easier way to do this– any thoughts? If not, what can I do to get MySQL to advance to the next row the next time the loop is run? I thought it was supposed to do that anyway with mysql_fetch_array.
And yes, I’ve looked at fputcsv, but I can’t seem to get any data to pass. The CSV file always comes up blank when I try to pass an array using fputcsv and getting the array via mysql_fetch_array, mysql_fetch_assoc, or mysql_fetch_row.
I’ve been learning as I go, and this is one of those times when I just haven’t learned something in order to keep moving forward. And I don’t know that much, either.
My code, or at least as much as is necessary:
$result = mysql_query("SELECT id FROM student_history WHERE username='$username'");
$numrows = mysql_num_rows($result);
if (!$result) {
die("Query to show fields from table failed!:" .mysql_error());
}
$write = fopen("exportedmagic.csv", 'w') or die ("Can't create/open file to write! Drats!");
fwrite($write, "ID, Username, Class, Status, Date, Time\n");
while($numrows > 0) {
$query = "SELECT id, username, class, status, date, time FROM student_history WHERE username='$username'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$id = $row['id'];
$username = $row['username'];
$class = $row['class'];
$status = $row['status'];
$date = $row['date'];
$time = $row['time'];
fwrite($write, $id .", " .$username .", " .$class .", " .$status .", " .$date .", " .$time ."\n");
$numrows--;
}
Try changing to-
With using
while($numrows > 0){$query= ... $numrows--;you are redoing the query every time you go through the loop.Also, instead of using
fwrite()you can usefputcsv()which makes it possible to add the row without needing to iterate through each column value in your current code.Note: you will want to look at updating to either
mysqli_*orPDOas themysql_*extension is depreciated.