Php+mysql+jquery Implementing File Download Count

Source: Internet
Author: User

Data Sheet
CREATE TABLE IF NOT EXISTS `downloads` ( 
  `id` int(6) unsigned NOT NULL AUTO_INCREMENT, 
  `filename` varchar(50) NOT NULL, 
  `savename` varchar(50) NOT NULL, 
  `downloads` int(10) unsigned NOT NULL DEFAULT ‘1‘, 
  PRIMARY KEY (`id`), 
  UNIQUE KEY `filename` (`filename`) 
) ENGINE=MyISAM  DEFAULT CHARSET=utf8; 

HTML<div id= "Demo" > <ulclass= "FileList" > </ul> </div>CSS#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; Width200px} ul. filelist Li A{display:block;padding:8px;} UL. filelist li A:hover. Download{display:Block;} Span. Download{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;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} Span. Downcount{color:#999;padding:5px;position:absolute; margin-left:10px;text-decoration:none;}

  jquery Front-end page jquery mainly completes two tasks, one is to read the file list asynchronously through Ajax and show, second, in response to the user click event, the corresponding file download number +1 , to see the code: $ (Function  () { $.ajax ({//Asynchronous Request type: ' GET ',  URL: ' filelist.php ',  dataType: ' json ',  cache:false ,  beforesend:function  () {$ (". FileList"). HTML ("<li class= ' load ' > Loading ...</li>" );},  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 "tit le= "Downloads" > ' +array[' Downloads ']+ '  </span> <span class= ' Download ' > click to download </span></a> ;</li> ' ;}); $ (". FileList").  html (li);} 
span>
$ (' ul.filelist a '). On (' click ', Function () {         var count = $ ('. Downcount ');         Count.text (parseint (Count.text ()) +1); Download Count +1    



First, after the page is loaded, send a Get-form Ajax request through $.ajax () to the background filelist.php, and when Filelist.php succeeds, receives the returned JSON data, traversing the JSON data object through $.each (), Constructs an HTML string and adds the resulting string to the UL. FileList, a list of files in the demo is formed. Then, when you click on the file download, the download count is incremented by the Click event in response to the dynamically added list element.
PHP in order to better understand, we divide two PHP files, one is FileList. PHP, used to read the data in the MySQL data table, and output the data in JSON format to 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. In fact, there is a database connection file conn. php, 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.
conn.php

<?php
$host = "localhost";
$db _user= "root";
$db _pass= "";
$db _name= "Test";
$timezone = "Asia/shanghai";

$link =mysqli_connect ($host, $db _user, $db _pass);

mysqli_select_db ($link, $db _name);
Mysqli_query ($link, "SET names UTF8");
Header ("content-type:text/html; Charset=utf-8 ");

?>

  
filelist.php
require' conn.php ';//connecting to a 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 ']         ); }     EchoJson_encode ($data); } Download. php according to the URL parameter, query to get the corresponding data, detect the existence of the file to be downloaded, if present, update the corresponding data download number +1, and use header () to implement 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 file name to be saved to local after download. In general, we use the background upload program will be uploaded files renamed and saved to the server, a common date-time named file, one of the benefits of this is to avoid the file name duplication and Chinese name garbled situation. The files we download to local can use the header ("content-disposition:attachment; Filename= ".$filename) to set the file name to an easily identifiable filename.
download.php

require(' conn.php ');//connecting to a database$id= (int)$_get[' ID ']; if(!isset($id) ||$id==0) die(' parameter Error! ')); $query=mysql_query($link, "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 code$savename=$row[' Savename '];//the actual save name on the server$myfile= ' file/'.$savename; if(file_exists($myfile)){//if the file exists//updates the number of downloads Mysqli_query($link, "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); Exit; }Else{ Echo' File does not exist! ‘; }

Php+mysql+jquery Implementing File Download Count

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: info-contact@alibabacloud.com 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.