Home Web Front-end JS Tutorial Ajax+mysql creates message board function

Ajax+mysql creates message board function

Apr 02, 2018 pm 02:58 PM
Function message board

This time I will bring you the function of making a message board with Ajax+mysql. What are the precautions for making a message board with Ajax+mysql? The following is a practical case, let's take a look.

Recently I made a small demo to realize the data interaction between Ajax and MySQL. The js part uses jq, the backend uses php, and the database is mysql. I will make a node+mongodb version later.

I won’t go into details about the use and installation of mysql. I integrate Baidu xampp, Apache server and mysql database by myself, which is very easy to use.

First open the server and database. I first created an "eleven" database here, and then created a table called microblog (please note: I am using a high version of mysql here, and PHP is linked to the database. All methods use mysqli_ If the version is too low, please use the mysql_ method and modify the code yourself)
The following is the code part:

html page and js part:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title>微博留言板</title> 
    <style type="text/css"> 
      *{ 
        margin: 0; 
        padding: 0; 
      } 
      #box{ 
        width: 600px; 
        /*height: 500px;*/ 
        border: 2px solid rgb(85,85,85); 
        border-radius: 15px; 
        margin: 50px auto; 
        padding: 20px 10px 15px; 
        background-color: rgb(85,85,85); 
      } 
      #content{ 
        display: block; 
        resize: none; 
        width: 550px; 
        height: 200px; 
        margin: 0 auto; 
        border: 2px solid rgb(225,225,225); 
        border-radius: 10px; 
        text-align: center; 
        font-size: 30px; 
        background-color: rgb(225,225,225); 
      } 
      #content:focus{ 
        outline: none; 
        border: 2px solid rgb(225,225,225); 
        box-shadow: 0 0 15px rgb(225,225,225); 
      } 
      #btn{ 
        border: 2px solid rgb(255,204,0); 
        width: 80px; 
        height: 40px; 
        border-radius: 5px; 
        margin-top: 30px; 
        font-size: 17px; 
        cursor: pointer; 
        outline: none; 
        background-color: rgb(255,204,0); 
      } 
       
      .list{ 
        list-style: none; 
        background-color: rgb(249,249,249); 
        margin-top: 20px; 
      } 
      .list>li{ 
        padding: 20px 10px 10px; 
        border-bottom: 2px solid rgb(68,68,68); 
        font-size: 20px; 
        color: rgb(200,214,225); 
        position: relative; 
        word-break: break-word; 
        word-wrap: break-word; 
        background-color: rgb(85,85,85); 
         
      } 
      .list>li>.control{ 
        position: absolute; 
        bottom: 3px; 
        right: 5px; 
        font-size: 14px; 
      } 
      .list>li>p{ 
        margin-bottom: 25px; 
      } 
      .control span,.control em{ 
        display: inline-block; 
        margin-right: 15px; 
      } 
      .control em{ 
        color: darkblue; 
        cursor: pointer; 
      } 
      a{ 
        text-decoration: none; 
        color: darkred; 
      } 
      #page>a{ 
        display:inline-block; 
        width: 40px; 
        height: 30px; 
        margin-top: 10px; 
        text-align: center; 
        line-height: 30px; 
        font-size: 20px; 
        border-radius: 5px; 
        color: white; 
        background-color: rgb(51,21,70); 
      } 
      #head{ 
        color: rgb(200,214,225); 
        font-size: 30px; 
        height: 50px; 
        border-bottom: 2px solid rgb(68,68,68); 
        margin-bottom: 20px; 
      } 
    </style> 
  </head> 
  <body> 
    <p id="box"> 
      <p id="head"> 
        留言板 
      </p> 
      <p id="fill_in"> 
        <textarea id="content"></textarea> 
        <button id="btn">提交留言</button> 
      </p> 
      <!--留言列表--> 
      <p id="message_text"> 
        <ul class="list"> 
        </ul> 
      </p> 
      <!--分页--> 
      <p id="page"> 
        <a href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >1</a> 
        <a href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >2</a> 
      </p> 
    </p> 
  </body> 
  <script src="Jq/jquery-3.1.1.min.js"> 
</html>
Copy after login

Code display Not finished, here is part of the php code.
Continue with part 01, jq’s ajax request:

<script type="text/javascript"> 
    $(function(){ 
      $("#btn").on("click",function(){ 
        if ($("#content").val() == "") { 
          alert("~~客官,说一句再走呗~~"); 
          return; 
        }  
        else{ 
          $.ajax({ 
            type:"get", 
            url:"http://localhost/phpStudy/ajax03/message.php", 
            async:true, 
            dataType:"json", 
            data:{ 
              content:$("#content").val(), 
              act:"add" 
            }, 
            success:function(data){ 
//             var result = JSON.parse(data); 
              if (data.error==0) { 
                createLi(data.id,$("#content").val(),data.time); 
              } else{ 
                alert(data.msg); 
              } 
            } 
          }); 
        } 
         
      }); 
       
      //创建节点 
      function createLi(id,content,time){ 
        var html = $('<li><p>'+content+'</p><p class="control"><span>时间:'+time+'</span>顶:<em>0</em>踩:<em>0</em><a class="remove" href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a></p></li>'); 
          $(".list").prepend(html); 
          var h = html.height(); 
          html.height(0); 
          html.stop().animate({ 
            height:h 
          },300); 
          //删除 
          html.find(".remove").on("click",function(){ 
            html.stop().animate({ 
              height:0 
            },300,function(){ 
              html.remove(); 
            }) 
          }); 
      } 
    }) 
  </script>
Copy after login

This part is the php code part:

<?php 
  header("Content-type:text/html;charset=utf8"); 
   date_default_timezone_set("PRC"); 
   //链接数据库 
   $link = mysqli_connect("localhost", "root", "", "eleven"); 
   //设置数据库编码格式 
   mysqli_query($link, "set names utf8"); 
?>
Copy after login

Note: I wrote this part as public code because I am learning to do other things is called, so the following code will have

include_once "comment.php";
Copy after login

This line refers to other codes

<?php 
  /* 
   * 开发文档 
   * 1.用于提交的留言留言进行存储 
   * url:http://localhost/phpStudy/ajax03/message.php 
   * 提交方式:get 
   * 提交参数说明: 
   * content 必须 留言板内容 
   * act 必须 借口标识 
   * 返回参数说明 
   * 成功:{"error":"0","id":1,"time":"2016-11-30"} 
   * 失败:{"error":1,"msg":"留言失败,请重试"} 
   * 
   * 2.up 
   * id 必须 留言的id编号 
   * act 必须 接口标识 up 
   * 返回声明 
   * 成功:{"error":"0"} 
   * 失败:{"error":"1","msg":"点赞失败"} 
   * 
   * 3.分页(获取页码的接口); 
   * act 必须 接口标识 count 
   * 返回参数说明: 
   * 成功:{"error":"0","countPage":"3"}; 
   * 失败:{"error":"1","msg":"请求数据失败,请重试!"} 
   * 
   * 4.分页(点击页码跳转) 
   * url:http://localhost/phpStudy/ajax03/message.php 
   * 提交方式:get 
   * 提交参数说明: 
   * starPage 必须参数 页码索引值 
   * act 必须 接口标识 page 
   * 返回参数说明 
   * 成功:{"error":"0","data":[{},{},{},{},{}]} 
   * 失败:{"error":"1","msg":"数据查询失败,请重试!"} 
   * 
   */ 
   include_once "comment.php"; 
   $act = $_GET["act"];//接口请求标识 
   switch ($act) { 
    case &#39;add&#39;://提交留言 
      $content = $_GET["content"]; 
      $time = time(); 
      $times = date("Y-m-d H:i:s",$time); 
      $query = "INSERT INTO microblog(id,content,time) VALUES(null,&#39;{$content}&#39;,&#39;{$times}&#39;)"; 
      mysqli_query($link,$query); 
      $insertId = mysqli_insert_id($link); 
      if($insertId>0){ 
        $arr = ["error"=>0,"id"=>$insertId,"time"=>$times]; 
        echo json_encode($arr);//将数组转化为json,方便前端使用 
      } 
      else{ 
        $arr = ["error"=>1,"msg"=>"留言失败,请重试!"]; 
        echo json_encode($arr);//将数组转化为json,方便前端使用 
      } 
      break; 
       
    case 'up': 
      $id = $_GET['id']; 
      $search = "SELECT up FROM microblog WHERE id = $id"; 
      $result = mysqli_query($link, $search); 
      $upNum = mysqli_fetch_row($result)[0]; 
      $upNum++; 
      $query = "UPDATE microblog SET up='{$upNum}' WHERE id = '{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)){//更新数据成功 
        echo '{"error":"0"}'; 
      } 
      else{//更新失败 
        echo '{"error":"1","msg":"点赞失败!"}'; 
      } 
      break; 
       
    case 'down': 
      $id = $_GET['id']; 
      $search = "SELECT down FROM microblog WHERE id = $id"; 
      $result = mysqli_query($link, $search); 
      $downNum = mysqli_fetch_row($result)[0]; 
      $downNum++; 
      $query = "UPDATE microblog SET down='{$downNum}' WHERE id = '{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)){//更新数据成功 
        echo '{"error":"0"}'; 
      } 
      else{//更新失败 
        echo '{"error":"1","msg":"踩失败!"}'; 
      } 
      break;  
    case 'remove': 
      $id = $_GET['id']; 
      $query ="DELETE FROM microblog WHERE id='{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)>0){//删除数据成功 
        echo '{"error":"0"}'; 
      } 
      else{ 
        echo '{"error":"1","msg":"删除失败!"}'; 
      } 
      break; 
    case 'count'://返回总页码 
      $query = "SELECT count(id) FROM   microblog"; 
      $result = mysqli_query($link, $query); 
      $count = mysqli_fetch_row($result)[0];//以索引数组形式返回查询结果 
      $countPage = ceil($count/5); 
      echo '{"error":"0","countPage":"'.$countPage.'"}'; 
      break;  
    case 'page'://点击分页或者是页面第一次加载 
      $index = $_GET["num"]*5; 
      $search = "SELECT * FROM microblog ORDER BY id DESC LIMIT {$index},5";//倒叙查询留言 
      $result = mysqli_query($link, $search); 
      $arr = [];//存查询出来的数据 
      while($row = mysqli_fetch_assoc($result)){ 
        array_unshift($arr,$row); 
      } 
//     print_r($arr); 
//     {"error":"0","info":[{},{},{},{},{}]} 
      $resultArr = ["error"=>"0","info"=>$arr]; 
      echo json_encode($resultArr); 
      break; 
     
   } 
?>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!

Recommended reading:

What is the difference between synchronization and asynchronous implementation using Ajax

AJAX cross-domain request JSONP to obtain JSON data Detailed explanation of steps (with code)

The above is the detailed content of Ajax+mysql creates message board function. 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)

What functions does Doubao app have? What functions does Doubao app have? Mar 01, 2024 pm 10:04 PM

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

What is a Bluetooth adapter used for? What is a Bluetooth adapter used for? Feb 19, 2024 pm 05:22 PM

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

See all articles