Table of Contents
PHP Mysql jQuery file download count statistics example explanation,
Home Backend Development PHP Tutorial PHP Mysql jQuery file download count statistics example explanation, _PHP tutorial

PHP Mysql jQuery file download count statistics example explanation, _PHP tutorial

Jul 12, 2016 am 09:07 AM
jquery mysql php Download Document

PHP Mysql jQuery file download count statistics example explanation,

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; 
Copy after login

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> 
Copy after login

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;} 
Copy after login

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); 
} 
Copy after login

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 '文件不存在!'; 
} 
Copy after login

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&#63;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 
  }); 
}); 
Copy after login

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1060095.htmlTechArticlePHP Mysql jQuery file download count statistics example explanation, in the project we need to count the number of downloads of the file, each time the user downloads it file, the corresponding download count is increased by 1, similar applications are in...
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How does MySQL differ from Oracle? How does MySQL differ from Oracle? Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

See all articles