Ajax and mysql data interaction to create message board function
This article mainly introduces Ajax and mysql data interaction in detail to realize the message board function. It has certain reference value. Interested friends can refer to it.
I recently made a small The demo implements the data interaction between Ajax and MySQL. The js part uses jq, the backend uses php, and the database is mysql. A node mongodb version will be released 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>
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>
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"); ?>
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";
. This line refers to other codes
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; } ?>
. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Instances of ajax responding to json strings and json arrays (graphic tutorial)
Ajax synchronization and asynchronous issues Brief analysis and solutions
Two methods for Ajax to solve redundant refresh
The above is the detailed content of Ajax and mysql data interaction to create message board function. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools