I have a mysql database and I would like to search with a query - catalogue name (catn) - and then download the whole row associate with that query. I have wrote a php code but nothing is writing to the file. The download starts after clicking on the Download button but the file is empty. Could anyone please help me with this?
I have two php files.
The first one has the code for the button:
<html>
<body>
<form action="download.php" method="post"> <pre> Catalogue number <span class="inner-pre"> <input name="catnq" input type="text";/>
<input type="submit" value="Download";/>
</pre></form>
</body>
</html>
The second file - download.php - has the code for the downloading. I have omitted the part of code regarding the connection to mysql.
<?php
if (($_POST['catnq'] != "")) {
$fp = fopen('file.csv', 'w');
$query = "select * from Compounds where catn =";
$query = $query." '".get_post('catnq')."'";
$sqlsearch = mysql_query($query);
while($row = mysql_fetch_array($sqlsearch)){
$name = $row['catn'];
fwrite($fp, $name);
}
fclose($fp);
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
}
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>
Solution
I have managed to make it work with the help of the comments (thank you!) and here is the code:
<?php
$input_user = $_POST["catnq"];
if (($_POST['catnq'] != "")) {
$fp = fopen('file.csv', 'w');
$query = "select * from Compounds where catn = '$input_user' ";
$sqlsearch = mysql_query($query);
while($row = mysql_fetch_array($sqlsearch)){
$name = $row['catn'];
echo $name;
echo "\n";
}
readfile('file.csv');
fclose($fp);
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
}
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>