Monday, December 7, 2009

Downloading Files From MySQL Database

When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.

The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3.

nclude 'library/config.php';
include 'library/opendb.php';

$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty
";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>








When you click the download link, the $_GET['id'] will be set. We can use this id to identify which files to get from the database. Below is the code for downloading files from MySQL Database.

Example :
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database

include 'library/config.php';
include 'library/opendb.php';

$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";

$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);

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

include 'library/closedb.php';
exit;
}

Before sending the file content using echo first we need to set several headers. They are :

  1. header("Content-length: $size")
    This header tells the browser how large the file is. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is. That way anyone who download the file can predict how long the download will take.
  2. header("Content-type: $type")
    This header tells the browser what kind of file it tries to download.
  3. header("Content-Disposition: attachment; filename=$name");
    Tells the browser to save this downloaded file under the specified name. If you don't send this header the browser will try to save the file using the script's name (download.php).

After sending the file the script stops executing by calling exit.

error---Cannot modify header information - headers already sent

This error happens because some data was already sent before we send the header. As for the error message above it happens because i "accidentally" add one space right after the PHP closing tag ( ?> ) in config.php file. So if you see this error message when you're sending a header just make sure you don't have any data sent before calling header().

upload phto

1.

2. Photo
3.
4.
5.


$max_file)) {
$error= "ONLY jpeg images under 1MB are accepted for upload";
}
}else{
$error= "Select a jpeg image for upload";
}
//Everything is ok, so we can upload the image.
if (strlen($error)==0){

if (isset($_FILES["image"]["name"])){

move_uploaded_file($userfile_tmp, $large_image_location);
chmod ($large_image_location, 0777);

$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
//Scale the image if it is greater than the width set above
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
//Delete the thumbnail file so the user can create a new one
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
}
//Refresh the page to show the new uploaded image
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
}

Pagination in php

$sql = "SELECT COUNT(*) FROM users";
$result = mysql_query($sql) OR die(mysql_error());
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < currentpage =" 1;" offset =" ($currentpage" term =" $_GET['artist'];" artist =" mysql_real_escape_string($_GET['artist']);" href="http://www.blogger.com/%5C%22admin.php%5C%22">Return to admin section!


";

echo "
Uploads:
";

$sql = "SELECT * FROM users LIMIT $offset, $rowsperpage";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
$result=mysql_query($sql);
while ($list = mysql_fetch_array($result))
{
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";


}
echo "";
echo "
idnamegenderdobemailphoneusernamestatusdeleteedit
",$list['id'],"",$list['name'],"", $list['gender'],"",$list['dob'],"",$list['email'],"",$list['phone'],"",$list['username'],"",$list['status'],"", "";
echo "
","\">Deleteuser","", "";
echo "
","\">updatestatus
","
";
echo "

";
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << href="http://www.blogger.com/%7B$_SERVER%5B" php_self="" currentpage="1'"><< "; // get previous page num $prevpage = $currentpage - 1; // show < href="http://www.blogger.com/%7B$_SERVER%5B" php_self="" currentpage="$prevpage'">< "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [$x] ";
// if not current page...
} else {
// make it a link
echo " $x ";
} // end else
} // end if
} // end for

// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " NEXT PAGE ";
// echo forward link for lastpage
echo " a href="http://www.blogger.com/%7B$_SERVER%5B" php_self="" currentpage="$totalpages'"> LAST PAGE ";
} // end if
echo "
";

email me to get the code of this coding

rawatsingharun@gmail.com