Ajax and mysql DATA interaction to create a message board function (full), ajaxmysql

Source: Internet
Author: User
Tags mongodb version

Ajax and mysql DATA interaction to create a message board function (full), ajaxmysql

Recently, I made a small demo to implement data interaction between Ajax and MySQL. jq is used in js, php is used in the background, and mysql is used in the database, A node + mongodb version will be available later.

I will not talk about the use and installation of mysql. Baidu xampp, Apache server and mysql database are integrated on its own, which is very easy to use.

First, open the server and database. Here, I first created a "eleven" database, and below I created a table called microblog (Note: I am using a high version of mysql here, mysqli _ is used to link php to the database. if the version is too low, use the mysql _ method to modify the code)
The Code section is as follows:

Html page and js section:

<! DOCTYPE html> 

The code is not displayed. Below is some php code.
In Part 01, jq's ajax request:

<Script type = "text/javascript"> $ (function () {$ ("# btn "). on ("click", function () {if ($ ("# content "). val () = "") {alert ("~~ Guest, say a word and then go ~~ "); 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) ;}}) ;}}); // create a node function createLi (id, content, time) {var html = $ ('<li> <p>' + content + '</p> <div class = "control"> <span> time: '+ time +' </span> top: <em> 0 </em> step on: <em> 0 </em> <a class = "remove" href = "datagript: void (0) "rel =" external nofollow "> Delete </a> </div> </li> '); $ (". list "). prepend (html); var h = html. height (); html. height (0); html. stop (). animate ({height: h}, 300); // delete 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 database $ link = mysqli_connect ("localhost ", "root", "", "eleven"); // sets the database encoding format mysqli_query ($ link, "set names utf8");?>

Note: I have written this part of public code, because I called it when learning to do other things, so the following code will

include_once "comment.php"; 

This line references other code

<? Php/** development document ** 1. Store the submitted message * url: http://localhost/phpStudy/ajax03/message.php * Submission method: get * Submission parameter description: * content must be the message board content * act must be used to identify * return parameter description * success: {"error": "0", "id ": 1, "time": "2016-11-30"} * failure: {"error": 1, "msg": "Message failed, please try again "} ** 2.up * id must be the id number of the Message * act must be the interface identification up * return Declaration * success: {" error ":" 0 "} * failed: {"error": "1", "msg": "thumb up failed"} ** 3. pagination (page number Retrieval Interface); * act must identify the interface count * return parameter description: * success: {"error": "0", "countPage": "3 "}; * failed: {"error": "1", "msg": "data request failed. Please try again! "} ** 4. pagination (click to jump to the page number) * url: http://localhost/phpStudy/ajax03/message.php * Submission method: get * Submission parameter description: * starPage must be a page number index value * act must be an interface identification page * return parameter description * success: {"error": "0 ", "data": [{},{},{},{},{}]} * failure: {"error": "1", "msg ": "Data Query failed. Please try again! "} **/Include_once" comment. php "; $ act = $ _ GET [" act "]; // Interface request ID switch ($ act) {case 'add ': // submit a message $ content = $ _ GET ["content"]; $ time = time (); $ times = date ("Y-m-d H: I: s ", $ time); $ query =" insert into microblog (id, content, time) VALUES (null, '{$ content}', '{$ times }') "; mysqli_query ($ link, $ query); $ insertId = mysqli_insert_id ($ link); if ($ insertId> 0) {$ arr = [" error "=> 0, "id" => $ insertId, "time" => $ times]; Echo json_encode ($ arr); // convert the array to json for front-end use} else {$ arr = ["error" => 1, "msg" => "Message failed. Please try again! "]; Echo json_encode ($ arr); // convert the array to json for convenient front-end use} 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) {// data update successful echo '{"error": "0"}';} else {// update failed ec Ho' {"error": "1", "msg": "thumb up failed! "} ';} Break; case 'Demo': $ 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) {// Data Update Success echo '{"error": "0 "}';} else {// update failed echo '{"error": "1", "msg": "failed! "} ';} Break; case 'delete': $ id = $ _ GET ['id']; $ query = "delete from microblog WHERE id = '{$ id}'"; mysqli_query ($ link, $ query); if (mysqli_affected_rows ($ link)> 0) {// The data is successfully deleted. echo '{"error": "0"}';} else {echo '{"error": "1", "msg ": "deletion failed! "} ';} Break; case 'Count': // returns the total page number $ query =" SELECT count (id) FROM microblog "; $ result = mysqli_query ($ link, $ query); $ count = mysqli_fetch_row ($ result) [0]; // return the query result in the form of an index array $ countPage = ceil ($ count/5 ); echo '{"error": "0", "countPage ":"'. $ countPage. '"}'; break; case 'page': // click the page or load $ index = $ _ GET [" num "] * 5 for the first time on the page; $ search = "SELECT * FROM microblog order by id desc limit {$ index}, 5"; // flashback query message $ result = Mysqli_query ($ link, $ search); $ arr = []; // Save the queried data 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 all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.