Home php教程 php手册 PHP+Mysql+jQuery文件下载次数统计实例讲解

PHP+Mysql+jQuery文件下载次数统计实例讲解

Jun 06, 2016 pm 07:41 PM
jquery mysql php Download Document

这篇文章主要内容是关于PHP+Mysql+jQuery文件下载次数统计实例讲解

项目中我们需要统计文件的下载次数,用户每下载一次文件,相应的下载次数加1,类似的应用在很多下载站中用到。本文结合实例使用PHP+Mysql+jQuery,实现了点击文件,下载文件,次数累加的过程,整个过程非常流畅。

PHP+Mysql+jQuery文件下载次数统计实例讲解

准备工作
本实例需要读者具备PHP、Mysql、jQuery以及html、css等相关的基本知识,在开发示例前,需要准备Mysql数据表,本文假设有一张文件下载表downloads,用来记录文件名、保存在文件服务器上的文件名以及下载次数。前提是假设下载表中已存在数据,这些数据可能来自项目中的后台上传文件时插入的,以便我们在页面中读取。downloads表结构如下:

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;

您也可以直接下载Demo,导入SQL文件,数据都有了。
HTML
我们在index.html页面body中加入如下HTML结构,其中ul.filelist用来陈列文件列表,现在它里面没有内容,我们将使用jQuery来异步读取文件列表,所以别忘了,我们还需要在html中加载jQuery库文件。

CSS
为了让demo更好的展示页面效果,我们使用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; 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
为了更好的理解,我们分两个PHP文件,一个是filelist.php,用来读取mysql数据表中的数据,并输出为JSON格式的数据用来给前台index.html页面调用,,另一个是download.php,用来响应下载动作,更新对应文件的下载次数,并且通过浏览器完成下载。filelist.php读取downloads表,并通过json_encode()将数据以JSON格式输出,这样是为下面的Ajax异步操作准备的。

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根据url传参,查询得到对应的数据,检测要下载的文件是否存在,如果存在,则更新对应数据的下载次数+1,并且使用header()实现下载功能。值得一提的是,使用header()函数,强制下载文件,并且可以设置下载后保存到本地的文件名称。一般情况下,我们通过后台上传程序会将上传的文件重命名后保存到服务器上,常见的有以日期时间命名的文件,这样的好处之一就是避免了文件名重复和中文名称乱码的情况。而我们下载到本地的文件可以使用header("Content-Disposition: attachment; filename=" .$filename )将文件名设置为易于识别的文件名称。

require('conn.php');//连接数据库 $id = (int)$_GET['id']; if(!isset($id) || $id==0) die('参数错误!'); $query = mysql_query("select * from downloads where"); $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"); //下载文件 $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
前端页面jQuery主要完成两个任务,一是通过Ajax异步读取文件列表并展示,二是响应用户点击事件,将对应的文件下载次数+1,来看代码:

$(function(){ $.ajax({ //异步请求 type: 'GET', url: 'filelist.php', dataType: 'json', cache: false, beforeSend: function(){ $(".filelist").html("

  • 正在载入...
  • "); }, success: function(json){ if(json){ var li = ''; $.each(json,function(index,array){ li = li + '
  • '+array['file']+ ''+array['downloads']+' 点击下载
  • '; }); $(".filelist").html(li); } } }); $('ul.filelist a').live('click',function(){ var count = $('.downcount',this); count.text( parseInt(count.text())+1); //下载次数+1 }); });
    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 Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    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
    1664
    14
    PHP Tutorial
    1269
    29
    C# Tutorial
    1248
    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.

    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.

    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.

    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.

    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.

    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.

    Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

    AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

    MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

    MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

    See all articles