Home > Backend Development > PHP Tutorial > PHP Mysql and jQuery implement file download count statistics

PHP Mysql and jQuery implement file download count statistics

WBOY
Release: 2016-07-25 08:55:34
Original
1116 people have browsed it
  1. CREATE TABLE IF NOT EXISTS `downloads` (
  2. `id` int(6) unsigned NOT NULL AUTO_INCREMENT,
  3. `filename` varchar(50) NOT NULL,
  4. `savename` varchar(50) NOT NULL,
  5. `downloads` int(10) unsigned NOT NULL DEFAULT '1',
  6. PRIMARY KEY (`id`),
  7. UNIQUE KEY `filename` (`filename`)
  8. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy code

You can also directly download the Demo, import the SQL file, and the data is all there.

Download address: Source code for PHP file download count statistics.

Second, HTML part

Add the following HTML structure to the index.html page body, where ul.filelist is used to display the file list. Now it has no content, and jQuery will be used to read the file list asynchronously. You also need to load the jQuery library file in html.

Copy code

Three, CSS part In order to allow the demo to better display the page effect, CSS is used 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.

  1. #demo{width:728px;margin:50px auto;padding:10px;border:1px solid #ddd;background-color:#eee;}
  2. ul.filelist li{background:url("img/ bg_gradient.gif") repeat-x center bottom #F5F5F5;
  3. border:1px solid #ddd;border-top-color:#fff;list-style:none;position:relative;}
  4. ul.filelist li.load{background :url("img/ajax_load.gif") no-repeat; padding-left:20px;
  5. border:none; position:relative; left:150px; top:30px; width:200px}
  6. ul.filelist li a{display :block;padding:8px;}
  7. ul.filelist li a:hover .download{display:block;}
  8. span.download{background-color:#64b126;border:1px solid #4e9416;color:white;
  9. display: none;font-size:12px;padding:2px 4px;position:absolute;right:8px;
  10. text-decoration:none;text-shadow:0 0 1px #315d0d;top:6px;
  11. -moz-border-radius: 3px;-webkit-border-radius:3px;border-radius:3px;}
  12. span.downcount{color:#999;padding:5px;position:absolute; margin-left:10px;text-decoration:none;}
Copy code

Four, PHP part

For better understanding, it is divided 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 for calling the front-end index.html page. The other is download.php, used to respond to download actions , update the number of downloads of the corresponding file, and complete the download through the browser. In fact, there is also a database connection file conn.php, which has been packaged in the download compressed package. Click here to download. 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.

  1. require 'conn.php'; //Connect to the database
  2. $result = mysql_query("SELECT * FROM downloads");
  3. if(mysql_num_rows($result)){
  4. while($ row=mysql_fetch_assoc($result)){
  5. $data[] = array(
  6. 'id' => $row['id'],
  7. 'file' => $row['filename'],
  8. 'downloads '=> $row['downloads']
  9. );
  10. }
  11. echo json_encode($data);
  12. }
Copy code

download.php passes parameters according to the url, queries to get the corresponding data, detects whether the file to be downloaded exists, and if it exists, updates the number of downloads of the corresponding data by +1, and uses header() to implement the download function. It is worth mentioning that using the header() function , force the file to be downloaded, and you can set the file name to be saved locally after downloading.

Under normal circumstances, the uploaded file will be renamed and saved to the server through the background upload program. 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 downloaded locally, you can use header("Content-Disposition: attachment; filename=" .$filename) to set the file name to an easily identifiable file name.

  1. require('conn.php'); //Connect to the database
  2. $id = (int)$_GET['id'];
  3. if(!isset($id) | | $id==0) die('Wrong parameter!');
  4. $query = mysql_query("select * from downloads where id='$id'");
  5. $row = mysql_fetch_array($query);
  6. if( !$row) exit;
  7. $filename = iconv('UTF-8','GBK',$row['filename']);//Please pay attention to the conversion encoding of the Chinese name
  8. $savename = $row['savename']; //Actual save name on the server
  9. $myfile = 'file/'.$savename;
  10. if(file_exists($myfile)){//If the file exists
  11. //Update download times
  12. mysql_query("update downloads set downloads =downloads+1 where id='$id'");
  13. //Download file
  14. $file = @ fopen($myfile, "r");
  15. header("Content-type: application/octet-stream");
  16. header("Content-Disposition: attachment; filename=" .$filename );
  17. while (!feof($file)) {
  18. echo fread($file, 50000);
  19. }
  20. fclose($file);
  21. exit ;
  22. }else{
  23. echo 'The file does not exist! ';
  24. }
Copy code

5, jQuery part 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 increase the number of downloads of the corresponding file by 1.

Code:

  1. $(function(){
  2. $.ajax({ //Asynchronous request
  3. type: 'GET',
  4. url: 'filelist.php',
  5. dataType: 'json',
  6. cache: false,
  7. beforeSend: function(){
  8. $(".filelist").html("
  9. Loading...
  10. ");
  11. } ,
  12. success: function(json){
  13. if(json){
  14. var li = '';
  15. $.each(json,function(index,array){
  16. li = li + '
  17. '+array['file']+
  18. ''+ array['downloads']+'
  19. Click to download
  20. ';
  21. });
  22. $( ".filelist").html(li);
  23. }
  24. }
  25. });
  26. $('ul.filelist a').live('click',function(){
  27. var count = $('.downcount' ,this);
  28. count.text( parseInt(count.text())+1); //Number of downloads+1
  29. });
  30. });
Copy code

First, the page is loaded Finally, send an Ajax request in the form of GET to the background filelist.php through $.ajax(). When filelist.php responds successfully, it receives the returned json data, traverses the json data object through $.each(), and constructs an 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 a commonly used Ajax case. Of course, there is also the knowledge of PHP combined with mysql to achieve downloading. I hope it will be helpful to everyone.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template