Page 1 of 1

how to do a download from database using php/mysql

Posted: Thu Jan 21, 2016 3:18 am
by untz
hi, i need help from downloading a file on database, i create a download.php and when i press in the button i download a file named index.html, and isn't what i want
this is my code on download.php :

Code: Select all


<?php
if(isset($_GET['id']))
{
include (config/config.php);

// query the server for the file
$id = $_GET['id_ficheiro'];
$query = "SELECT Ficheiro FROM ficherio WHERE id_ficheiro = '$id'";
$result  = mysql_query($query) or die(mysql_error());

// define results into variables
$name=mysql_result($result,0,"Ficheiro");
$size=mysql_result($result,0,"size");
$type=mysql_result($result,0,"type");
$content=mysql_result($result,0,"content");

header("Content-disposition: attachment; filename=$Ficheiro");
header("Content-length: $size");
header("Content-type: $type");
echo $content;

mysql_close();
}
else{
die("No file ID given...");
}

?> 
and on the index.php i have this:

Code: Select all

<td><a href='index.php?mod=download&id=$row->id_ficheiro'><button class='btn btn-success'> Download </button></a></td>
if someone can help i will apreciate

thank you

Re: how to do a download from database using php/mysql

Posted: Thu Jan 21, 2016 7:18 am
by Celauran
What errors are you getting?

Re: how to do a download from database using php/mysql

Posted: Thu Jan 21, 2016 8:43 am
by untz
when i press the button to download it, i download a file index.html, and is not what i pretend, i pretend a file like pdf, docx, xlsx or pptx..

Re: how to do a download from database using php/mysql

Posted: Thu Jan 21, 2016 10:38 am
by Christopher
You link should be either:

Code: Select all

echo "<td><a href=\'index.php?mod=download&id={$row->id_ficheiro}\"><button class=\"btn btn-success\"> Download </button></a></td>";
Or:

Code: Select all

<td><a href='index.php?mod=download&id=<?php echo $row->id_ficheiro; ?>"><button class="btn btn-success\"> Download </button></a></td>
It is standard practice to use only double quotes in HTML. Please check your HTML for consistency (e.g., class="foo' will cause incorrect parsing).

Re: how to do a download from database using php/mysql

Posted: Fri Jan 22, 2016 3:32 am
by untz
i try, but still doesn't work,i think the problem is on download.php, i dont' know, is the firsst time i'm trying to do this..

Re: how to do a download from database using php/mysql

Posted: Fri Jan 22, 2016 4:30 pm
by Christopher
Your query is for: "SELECT Ficheiro FROM ficherio WHERE id_ficheiro = '$id'" but later you try to use columns: size, type and content.

Don't use the mysql library. It is not longer supported. Use the mysqli or PDO libraries. I also recommend returning an associative array or object, instead of accessing each column.