Home Web Front-end JS Tutorial Detailed explanation of lottery program examples using jQuery, PHP and Mysql

Detailed explanation of lottery program examples using jQuery, PHP and Mysql

Jan 12, 2018 am 09:58 AM
jquery mysql php

This article mainly introduces jQuery+PHP+Mysql to implement the lottery program in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Lottery programs are widely used in real life. Due to different application scenarios, the lottery methods are also diverse. This article will use examples to explain how to use jQuery+PHP+MySQL to implement a simple lottery program similar to that commonly seen on TV.

View Demo

The lottery program in this example is to randomly select one number at a time from a large number of mobile phone numbers. As the winning number, it can be drawn multiple times, and the number that is drawn will not be drawn again. Lottery process: After clicking the "Start" button, the program obtains the number information and scrolls to display the numbers. When the "Stop" button is clicked, the numbers stop scrolling. The number displayed at this time is the winning number. You can click the "Start" button to continue the lottery.

HTML


<p id="roll"></p><input type="hidden" id="mid" value=""> 
<p><input type="button" class="btn" id="start" value="开始"> 
<input type="button" class="btn" id="stop" value="停止"></p> 
<p id="result"></p>
Copy after login

In the above code, we need a #roll to display the rolling number, #mid is It is used to record the ID of the number drawn, and then two buttons are needed to "start" and "stop" actions respectively. Finally, a #result is needed to display the result of the draw.

CSS

We use simple css to decorate the html page.


.demo{width:300px; margin:60px auto; text-align:center} 
#roll{height:32px; line-height:32px; font-size:24px; color:#f30} 
.btn{width:80px; height:26px; line-height:26px; background:url(btn_bg.gif) 
 repeat-x; border:1px solid #d3d3d3; cursor:pointer} 
#stop{display:none} 
#result{margin-top:20px; line-height:24px; font-size:16px; text-align:center}
Copy after login

Note that we set the button #stop to display:none by default so that only the "Start" button will be displayed at the beginning. After clicking "Start", the lottery is in progress. , a Stop button will appear.

jQuery

The first thing we need to achieve is to click the "Start" button, obtain the data for the lottery from the background through ajax, that is, the mobile phone number, and then use the timing Scroll to display mobile phone numbers. Note that the mobile phone numbers displayed each time are random, that is to say, they do not appear in a certain order. Let’s look at the following code:


$(function(){ 
  var _gogo; 
  var start_btn = $("#start"); 
  var stop_btn = $("#stop"); 
   
  start_btn.click(function(){ 
    $.getJSON(&#39;data.php&#39;,function(json){ 
      if(json){ 
        var obj = eval(json);//将JSON字符串转化为对象 
        var len = obj.length; 
        _gogo = setInterval(function(){ 
          var num = Math.floor(Math.random()*len);//获取随机数 
          var id = obj[num][&#39;id&#39;]; //随机id 
          var v = obj[num][&#39;mobile&#39;]; //对应的随机号码 
          $("#roll").html(v); 
          $("#mid").val(id); 
        },100); //每隔0.1秒执行一次 
        stop_btn.show(); 
        start_btn.hide(); 
      }else{ 
        $("#roll").html(&#39;系统找不到数据源,请先导入数据。&#39;); 
      } 
    }); 
  }); 
});
Copy after login

First We define variables to facilitate subsequent calls. Then, when the "Start" button is clicked, the page sends an Ajax request to the background data.php. Here we use jqeury's getJSON to complete the asynchronous request. When the background returns json data, we can convert the JSON string into the object obj through the eval() function, which is actually converting the json data into an array. At this time, we use setInterval to make a timer. The work that needs to be done in the timer is to randomly obtain the mobile phone number information in the array obj, and then display it on the page. Then run the timer every 0.1, thus achieving the effect of scrolling the lottery numbers. At the same time, the "Stop" button is displayed and the "Start" button is hidden. At this time, the lottery is in progress.

Next, let’s look at the work required for the “stop” action.


  stop_btn.click(function(){ 
    clearInterval(_gogo); 
    var mid = $("#mid").val(); 
    $.post("data.php?action=ok",{id:mid},function(msg){ 
      if(msg==1){ 
        var mobile = $("#roll").html(); 
        $("#result").append("<p>"+mobile+"</p>"); 
      } 
      stop_btn.hide(); 
      start_btn.show(); 
    }); 
  });
Copy after login

When you click the "Stop" button, it means the lottery is over. Use the clearInterval() function to stop the timer, obtain the ID of the drawn number, and then send the ID of the selected number to the background data.php for processing through $.post. The number that should be drawn needs to be marked in the database. If the background processing is successful, the front-end will add the winning number to the winning results, hide the "Stop" button, and display the "Start" button, and you can draw again.

Note that we use setInterval() and clearInterval() to set the timer and stop the timer. You can search on Google or Baidu for information on the use of these two functions.

PHP

data.php needs to do two things. First, read the mobile phone number information by connecting to the database (not including the winning number) , and then output it to the front-end by converting it into json format; second, by receiving the front-end request, modify the winning number status in the corresponding database, which means that the number has won the prize and will no longer be used as the lottery number next time.


include_once(&#39;connect.php&#39;); //连接数据库 
 
$action = $_GET[&#39;action&#39;]; 
if($action==""){ //读取数据,返回json 
  $query = mysql_query("select * from member where status=0"); 
    while($row=mysql_fetch_array($query)){ 
    $arr[] = array( 
      &#39;id&#39; => $row[&#39;id&#39;], 
      &#39;mobile&#39; => substr($row[&#39;mobile&#39;],0,3)."****".substr($row[&#39;mobile&#39;],-4,4) 
    ); 
  } 
  echo json_encode($arr); 
}else{ //标识中奖号码 
  $id = $_POST[&#39;id&#39;]; 
  $sql = "update member set status=1 where id=$id"; 
  $query = mysql_query($sql); 
  if($query){ 
    echo &#39;1&#39;; 
  } 
}
Copy after login

We can see that there is a field called status in the data table member. This field is used to identify whether the prize is won. 1 means you have won the prize, 0 means you have not won the prize. This background php program operates the database and then returns the corresponding information to the front end.

MYSQL

Finally, attach the member table structure information.


CREATE TABLE `member` ( 
 `id` int(11) NOT NULL auto_increment, 
 `mobile` varchar(20) NOT NULL, 
 `status` tinyint(1) NOT NULL default &#39;0&#39;, 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy after login

Regarding the lottery program, there will be different forms of expression according to the different needs of different applications. Next we will have an article describing how to implement lottery procedures based on different probabilities.

Related recommendations:

Examples of implementing lottery programs with php, jQuery and Mysql

JavaScript simple lottery program implementation code sharing

js annual meeting lottery program

The above is the detailed content of Detailed explanation of lottery program examples using jQuery, PHP and Mysql. For more information, please follow other related articles on the PHP Chinese website!

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
1655
14
PHP Tutorial
1255
29
C# Tutorial
1228
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

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.

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

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.

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...

See all articles