search
HomeBackend DevelopmentPHP TutorialPHP Mysql and jQuery implement file download count statistics

  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.



Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version