In the project we need to count the number of downloads of files. Every time a user downloads a file, the corresponding number of downloads increases by 1, similar The application is used in many download sites. This article uses PHP Mysql jQuery based on examples to realize the process of clicking files, downloading files, and accumulating times. The whole process is very smooth.
Preparation
This example requires readers to have basic knowledge of PHP, Mysql, jQuery, html, css, etc. Before developing the example, you need to prepare a Mysql data table. This article assumes that there is a file download table downloads to record files. name, the name of the file saved on the file server, and the number of downloads. The premise is that data already exists in the download table. This data may be 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(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;
You can also directly download the Demo, import the SQL file, and the data is all there.
HTML
We add the following HTML structure to the index.html page body. ul.filelist is used to display the file list. Now it has no content. We will use jQuery to read the file list asynchronously, so don’t forget, we also jQuery library files need to be loaded in html.
<div id="demo"> <ul class="filelist"> </ul> </div>
CSS
In order to allow the demo to better display the page effect, we use CSS to modify the page. The following code mainly sets the file list display effect. Of course, in the actual project, the corresponding style can be set as needed.
#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;} 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;}
PHP
For better understanding, we divide into two PHP files, one is filelist.php, which is used to read the data in the mysql data table and output the data in JSON format to call the front-end index.html page. The other is download.php, which is used to respond to the download action, update the number of downloads of the corresponding file, and complete the download through the browser. filelist.php reads the downloads table and outputs the data in JSON format through json_encode(), which is prepared for the following Ajax asynchronous operation.
require 'conn.php'; //连接数据库 $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 passes parameters according to the url, queries to obtain the corresponding data, detects whether the file to be downloaded exists, and if it exists, updates the download count of the corresponding data to 1, and uses header() to implement the download function. It is worth mentioning that the header() function is used to force the file to be downloaded, and the file name can be set to be saved locally after downloading. Under normal circumstances, we use the background upload program to rename the uploaded files and save them to the server. Commonly used files are named after date and time. One of the benefits of this is that it avoids duplication of file names and garbled Chinese names. For files we download locally, we can use header("Content-Disposition: attachment; filename=" .$filename) to set the file name to an easily identifiable file name.
require('conn.php');//连接数据库 $id = (int)$_GET['id']; if(!isset($id) || $id==0) die('参数错误!'); $query = mysql_query("select * from downloads where id='$id'"); $row = mysql_fetch_array($query); if(!$row) exit; $filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码 $savename = $row['savename']; //实际在服务器上的保存名称 $myfile = 'file/'.$savename; if(file_exists($myfile)){//如果文件存在 //更新下载次数 mysql_query("update downloads set downloads=downloads+1 where id='$id'"); //下载文件 $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 '文件不存在!'; }
jQuery
The jQuery on the front-end page mainly completes two tasks. One is to read the file list asynchronously through Ajax and display it. The other is to respond to the user's click event and download the corresponding file 1 times. Let's look at the code:
$(function(){ $.ajax({ //异步请求 type: 'GET', url: 'filelist.php', dataType: 'json', cache: false, beforeSend: function(){ $(".filelist").html("<li class='load'>正在载入...</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" title="下载次数">'+array['downloads']+'</span> <span class="download">点击下载</span></a></li>'; }); $(".filelist").html(li); } } }); $('ul.filelist a').live('click',function(){ var count = $('.downcount',this); count.text( parseInt(count.text())+1); //下载次数+1 }); });
First, after the page is loaded, send an Ajax request in the form of GET to the background filelist.php through $.ajax(). When filelist.php succeeds, receive the returned json data through $.each() Traverse the json data object, construct the html string, and add the final string to ul.filelist to form the file list in the demo.
Then, when the file is clicked to download, the click event of the dynamically added list element is responded to through live(), and the number of downloads is accumulated.
Finally, in fact, after reading this article, this is an Ajax case that we usually apply. Of course, there is also the knowledge of PHP combined with mysql to implement downloading. I hope it will be helpful to everyone.