Php+mysql+jquery File Download Count Example explain _php example

Source: Internet
Author: User
Tags jquery library

In the project, we need to download the number of files, users download the file every time, the corresponding download times plus 1, similar applications in many download stations. This article unifies the example to use the Php+mysql+jquery, realizes the click File, downloads the file, the number of cumulative process, the whole process is very smooth.

Preparatory work
This example needs the reader to have PHP, MySQL, jquery and HTML, CSS and other related basic knowledge, before developing the example, need to prepare the Mysql data table, this article assumes that there is a file download table downloads, to record the file name, The file name and number of downloads that are saved on the files server. The assumption is that the data already exists in the download table, which may have been inserted from the background upload file in the project so that we can read it in the page. The downloads table structure is as follows:

CREATE TABLE IF not EXISTS ' downloads ' ( 
 ' id ' int (6) unsigned not NULL auto_increment, 
 ' filename ' varchar (%) not NULL, 
 ' savename ' varchar NOT null, 
 ' downloads ' int (m) unsigned NOT null DEFAULT ' 1 ', 
 PRIMARY KEY (' id '), 
 UNIQUE KEY ' filename ' (' filename ') 
Engine=myisam DEFAULT Charset=utf8; 

You can also download the demo directly, import the SQL file, the data are available.
we add the following HTML structure to the body of the index.html page, where ul.filelist is used to display the list of files, and now there is no content in it, we will use jquery to read the list of files asynchronously, so don't forget that we also need to load the jquery library file in HTML 。

<div id= "Demo" > 
  <ul class= "filelist" > 

In order to let the demo better display the page effect, we use CSS to decorate the page, the following code mainly sets the file list to show the effect, of course, the actual project can be set according to the appropriate style.

 #demo {width:728px;margin:50px auto;padding:10px;border:1px solid #ddd; 
Background-color: #eee;} 
Ul.filelist Li{background:url ("img/bg_gradient.gif") repeat-x Center bottom #F5F5F5; 
border:1px solid #ddd Border-top-color: #fff; list-style:none;position:relative;} 
Ul.filelist Li.load{background:url ("Img/ajax_load.gif") no-repeat; padding-left:20px; Border:none; position:relative; left:150px; top:30px; 
width:200px} ul.filelist li a{display:block;padding:8px;} 
Ul.filelist li A:hover. download{display:block;{background-color: #64b126; border:1px solid #4e9416; color:white; 
DISPLAY:NONE;FONT-SIZE:12PX;PADDING:2PX 4px;position:absolute;right:8px; text-decoration:none;text-shadow:0 
0 1px #315d0d; top:6px; 
Span.downcount{color: #999;p adding:5px;position:absolute; margin-left:10px;text-decoration:none;} 

to get a better understanding, we divided two php files, One is filelist.php, used to read the data in the MySQL data table, and output the data in JSON format for the foreground index.html page call, the other is download.php, in response to the download action, update the corresponding file download times, and through the browser to complete the download. Filelist.php reads the downloads table and outputs the data in JSON format via Json_encode (), which is prepared for the following Ajax asynchronous operation.

Require ' conn.php '; Connection database 
$result = mysql_query ("Select * from Downloads"); 
if (mysql_num_rows ($result)) {while 
  ($row =mysql_fetch_assoc ($result)) { 
    $data [] = Array ( 
      ' id ' => $row [ ' id ', 
      ' file ' => $row [' filename '], 
      ' downloads ' => $row [' Downloads '] 
  echo Json_encode ($data); 

download.php according to the URL parameters, query to get the corresponding data, detect the existence of the file to download, if there is, update the corresponding data download number +1, and use header () to achieve the download function. It is worth mentioning that the header () function is used to force the download of the file, and you can set the name of the file to be saved locally after downloading. Under normal circumstances, we upload the program through the background will be uploaded files renamed to save to the server, the common has a date and time to name the file, one of the advantages is to avoid duplicate file names and Chinese name garbled situation. And we download to the local file can use header ("content-disposition:attachment; Filename= ". $filename) sets the file name to an easily identifiable filename.

Require (' conn.php ')//connection database 
$id = (int) $_get[' id ']; 
if (!isset ($id) | | | | $id ==0) die (' parameter error! '); 
$query = mysql_query ("Select * from Downloads where id= ' $id '"); 
$row = Mysql_fetch_array ($query); 
if (! $row) exit; 
$filename = Iconv (' UTF-8 ', ' GBK ', $row [' filename '])://Chinese name Note conversion encoding 
$savename = $row [' savename '];//actual save name on server 
$myfile = ' file/'. $savename; 
if (file_exists ($myfile)) {//If the file exists 
  //update download Count 
  mysql_query ("Update downloads set downloads=downloads+1 where Id= ' $id '); 
  Download file 
  $file = @ fopen ($myfile, "R"); 
  Header ("Content-type:application/octet-stream"); 
  Header ("content-disposition:attachment; Filename= ". $filename); 
  while (!feof ($file)) { 
    echo fread ($file, 50000); 
  Fclose ($file); 
} else{ 
  echo ' file does not exist! '; 

Front page jquery mainly completes two tasks, one is to read the file list and display through Ajax asynchronously, the second is to respond to the user clicks the event, the corresponding file download number +1, look at the code:

 $ (function () {$.ajax ({//Asynchronous Request type: ' Get ', url: ' filelist.php ', DataType : ' JSON ', Cache:false, Beforesend:function () {$ (". FileList"). HTML ("<li class= ' load ' > Loading ... </l 
    I> "); 
        }, Success:function (JSON) {if (JSON) {var li = '; $.each (Json,function (index,array) {li = li + ' <li><a href= ' download.php?id= ' +array[' id ']+ ' ' > ' +array [' File ']+ ' <span class= ' downcount ' title= ' downloads ' > ' +array[' Downloads ']+ ' </span> <span class= ' Download ' 
        > Click to download </span></a></li> '; 
      $ (". FileList"). html (LI); 
    $ (' ul.filelist a '). Live (' click ', function () {var count = $ ('. Downcount ', this); Count.text (parseint (Count.text ()) +1); 
Download Count +1}); 

First, after the page is loaded, a get-form Ajax request is sent through $.ajax () to the background filelist.php, and when Filelist.php succeeds, it receives the returned JSON data and traverses the JSON data object via $.each (). Constructs an HTML string and adds the resulting string to the ul.filelist to form a list of files in the demo.
Then, when you click on the file download, add the download number by using Live () to respond to the click event of the dynamically added list element.
Finally, actually read through this article, this is a commonly used in the Ajax case, and of course, PHP combined with MySQL implementation of the download knowledge, I hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.