I've got a script for creating a CSV file from a database table, which works fine except that it outputs all the data in the table, and I need it to output data only for the current logged in user. The app I'm developing is for users to be able to store lists of books they've read, want to read, etc., and I want to be able to allow them to download a list of their books they can import into Excel for example. (Would a CSV file be the best option for this, given that there's also OpenOffice etc. as well as MS Excel?)
I figured out that I needed to create a temporary table to use a select query to select only records belonging to the current logged-in user. I can access the data for the current user using WHERE username='$session->username'
.
I thought it would be as easy as creating the temporary table before I try to run the queries that output the data for use in the CSV file, and then drop the table afterwards, but I've tried the CSV creation code again with the temporary table created before the CSV stuff, and again the CSV file produced includes all the records for all users.
There's a configuration file that sets the database connection properties, but also the table to be used to create the file, as the variable $table
, and I've set this to be the name of the temporary table I'm trying to create.
This is the code I've got:
<?
$link = mysql_connect($host, $user, $pass) or die("Cannot connect to the database." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$temp = mysql_query("CREATE TEMPORARY TABLE books_temp SELECT * FROM books WHERE username='$session->username'");
$tempresult = mysql_query($temp);
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("d-m-Y") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$query = 'DROP TABLE books_temp';
$result = mysql_query($query);
exit;
?>
It works perfectly outputting all the data, but still outputs all the data when I try to use it with the temporary table. Incidentally, I've tried remove the instruction to drop the temporary table from the end as well, and that doesn't make any difference. Also, checking in PhpMyAdmin, it doesn't seem as though the temporary table's being created. I'm obviously doing something wrong here or missing something, but I've no idea what.