PHP advanced Ajax technology for MySQL database access

Source: Internet
Author: User

Before reading this article, we recommend that you refer to "php accessing MySQL database beginner" and "php accessing MySQL database intermediate smarty technology".

In the previous article, we have developed a program that can read databases and display data, and the program achieves good interface and logical separation. However, this program does not support adding, deleting, and modifying databases. Therefore, these features are added here. Each time you add, delete, or modify data, send a request to the background using Ajax, and then adjust the page display based on the returned results of the background. This method can reduce the burden on the server.

 

The following is a brief introduction to Ajax and a complete example:

Ajax is a browser technology independent of web server software. It is not a new programming language, but a technology used to create better, faster, and more interactive web applications. Using ajax, you can use the XMLHTTPRequest object of JavaScript to directly communicate with the server. In this way, you can exchange data with the Web server without reloading the page. At the same time, Ajax uses asynchronous data transmission (HTTP request) between the browser and the web server, so that the webpage can request a small amount of information from the server, rather than the whole page. Ajax manuals can access http://api.jquery.com/category/ajax/

 

The following is the most comprehensive program in this series-reading data from the t_student table of the test database and displaying it. It also supports adding, deleting, and modifying the t_student table through Ajax. On the interface function, the odd and even rows of the table are discolored and the mouse is discolored, making the program more beautiful.

The program is divided into 8 files, respectively, smarty2.php?smarty2.html=smarty2_head.php=smarty2.jsand smarty2.css, and the newly added insert. php, delete. php, and updata. php.

1. smarty2_head.php File

Define database-related constants and variable arrays. The database name, user name and password, and table name are defined here.

<?php// by MoreWindows( http://blog.csdn.net/MoreWindows )define(DB_HOST, 'localhost');define(DB_USER, 'root');define(DB_PASS, '111111');define(DB_DATABASENAME, 'test');define(DB_TABLENAME, 't_student');$dbcolarray = array('id', 'name', 'age');?>

2. smarty2.php File

<? PHP // By morewindows (http://blog.csdn.net/MoreWindows) header ("Content-Type: text/html; charset = UTF-8"); require ('.. /.. /smart_libs/smarty. class. PHP '); require_once ('smarty2 _ head. PHP '); date_default_timezone_set ("PRC"); // mysql_connect $ conn = mysql_connect (db_host, db_user, db_pass) or die ("Connect failed ". mysql_error (); mysql_select_db (db_databasename, $ conn); // Number of $ SQL = sprintf ("select count (*) from % S ", db_tablename); $ result = mysql_query ($ SQL, $ conn); if ($ result) {$ dbcount = mysql_fetch_row ($ result ); $ tpl_db_count = $ dbcount [0];} else {die ("query failed");} $ tpl_db_tablename = db_tablename; $ tpl_db_coltitle = $ dbcolarray; // table content $ tpl_db_rows = array (); $ SQL = sprintf ("select % s from % s", implode (",", $ dbcolarray), db_tablename ); $ result = mysql_query ($ SQL, $ conn); While ($ ROW = mysql_fetch_array ($ resu LT, mysql_assoc) // equivalent $ ROW = mysql_fetch_assoc ($ result) $ tpl_db_rows [] = $ row; mysql_free_result ($ result); mysql_close ($ conn ); $ TPL = new smarty; $ TPL-> assign ('db _ tablename', $ tpl_db_tablename); $ TPL-> assign ('db _ count', $ tpl_db_count ); $ TPL-> assign ('db _ coltitle', $ tpl_db_coltitle); $ TPL-> assign ('db _ rows ', $ tpl_db_rows ); $ TPL-> display('smarty2.html ');?>

3.smarty2.html

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

4. smarty2.js File

The row-Changing Effect of the table's mouse is added.

// In the first column of the table, find the row function searchidintable (tablerow, findid) {var I; var tablerownum = tablerow. length; for (I = 1; I <tablerownum; I ++) if ($ ("# Table TR: eq (" + I + ") TD: eq (0) "2.16.html () = findid) return I; Return-1;} // use CSS to control the color function settablerowcolor () {$ (" # Table TR: odd ").css (" background-color "," # e6e6fa "); $ (" # Table TR: Even ").css (" background-color "," # fff0fa "); $ ("# Table TR: odd "). hover (Function (){((This).css ("background-color", "orange" has been completed, function(){((this..css ("background-color", "# e6e6fa") ;}); $ ("# Table TR: even "2.16.hover(function({}(this}.css (" background-color "," orange "has been written, function({}(this}.css (" background-color "," # fff0fa ");});} // response to the edit button function editfun (ID, name, age) {$ ("# editdiv "). show (); $ ("# adddiv "). hide (); $ ("# editdiv_id "). val (ID); $ ("# editdiv_name "). val (name); $ ("# editdiv_age "). Val (AGE);} // responds to the Add button function addfun () {$ ("# editdiv "). hide (); $ ("# adddiv "). show () ;}// function inctablerowcount () {var TC =$ ("# tablerowcount" contains rows tc.html(parseint(tc.html () + 1) added to the number of records );} // function dectablerowcount () {var Tc = $ ("# tablerowcount" extends tc.html(parseint(tc.html ()-1);} // Add a row of function addrowintable (ID, name, age) {// Add a new line var appendstr = "<tr>"; appendstr + = "<TD>" + ID + "</TD>"; appe Ndstr + = "<TD>" + name + "</TD>"; appendstr + = "<TD>" + age + "</TD> "; appendstr + = "<TD> <input type = \" button \ "value = \" Edit \ "onclick = \" editfun (ID, name, age ); \ "/>"; appendstr + = "<input type = \" button \ "value = \" delete \ "onclick = \" deletefun (ID) \ "/> </TD>"; appendstr + = "</tr>"; $ ("# table "). append (appendstr); inctablerowcount ();} // modify a row of function updatarowintable (ID, newname, newage) {var I = search Idintable ($ ("# Table TR"), ID); if (I! =-1) {$ ("# Table TR: eq (" + I + ") TD: eq (1)" example .html (name! = ""? Name: ""); $ ("# Table TR: eq (" + I + ") TD: eq (2)" comment .html (age! = ""? Age: ""); $ ("# editdiv "). hide () ;}}// delete a row of function deleterowintable (ID) {var I = searchidintable ($ ("# Table TR"), ID); if (I! =-1) {// Delete the row in the table $ ("# Table TR: eq (" + I + ")"). remove (); settablerowcolor (); dectablerowcount () ;}}// add Delete modify Database Function to communicate with the server through Ajax function insertfun () {var name = $ ("# adddiv_name "). val (); var age = $ ("# adddiv_age "). val (); If (name = "" | age = "") {alert ("enter your name and age! "); Return;} // submit to server returns the ID of the inserted data $. post ("insert. PHP ", {Name: name, age: Age}, function (data) {If (Data =" F ") {alert (" insert date failed ");} else {addrowintable (data, name, age); settablerowcolor (); $ ("# adddiv "). hide () ;}}) ;}function deletefun (ID) {If (confirm ("are you sure you want to delete? ") {// Submit to server $. post ("Delete. PHP ", {ID: Id}, function (data) {If (Data =" F ") {alert (" delete date failed ");} else {deleterowintable (ID) ;}} function updatafun () {var ID =$ ("# editdiv_id "). val (); var name = $ ("# editdiv_name "). val (); var age = $ ("# editdiv_age "). val (); // submit to server $. post ("updata. PHP ", {ID: ID, name: name, age: Age}, function (data) {If (Data =" F ") {alert ("updata date failed");} else {updatarowintable (ID, name, age) ;}}$ (document ). ready (function () {settablerowcolor (); updatatablerowcount ();});

5.smarty2.css File

@charset "utf-8";h1{color:Red;text-align:center;}table th{  background-color:#7cfc00;  } 

6. Newly Added insert. php

Insert data into the database. The ID number of the newly inserted data is returned successfully, and the "f" error is returned ".

<?phprequire_once 'smarty2_head.php';//mysql_connect$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("connect failed" . mysql_error());mysql_select_db(DB_DATABASENAME, $conn);//params$name = $_POST['name'];$age = $_POST['age'];//insert db$sql = sprintf("INSERT INTO %s(name, age) VALUES('%s', %d)", DB_TABLENAME, $name, $age);$result=mysql_query($sql, $conn);if ($result)  echo mysql_insert_id($conn);else  echo "f";mysql_close($conn);?>

7. Newly Added Delete. php

If a row of records in the database is deleted by ID, "F" is returned successfully, and "T" is returned if the row fails ".

<?phprequire_once 'smarty2_head.php';//mysql_connect$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("connect failed" . mysql_error());mysql_select_db(DB_DATABASENAME, $conn); //params$id       = $_POST['id'];//delete row in db$sql = sprintf("delete from %s where id=%d", DB_TABLENAME, $id);$result = mysql_query($sql, $conn);mysql_close($conn);if ($result)  echo "t";else  echo "f";?>

8. Newly Added updata. php

Modify a row of records in the database based on the ID. "F" is returned for success, and "T" is returned for failure ".

<?phprequire_once 'smarty2_head.php';//mysql_connect$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("connect failed" . mysql_error());mysql_select_db(DB_DATABASENAME, $conn);  //params$id       = $_POST['id'];$name = $_POST['name'];$age = $_POST['age'];//updata db$sql = sprintf("update %s set name='%s',age=%d where id=%d", DB_TABLENAME, $name, $age, $id);$result=mysql_query($sql, $conn);mysql_close($conn);if ($result)  echo "t";else  echo "f";?>

The program running result is as follows (win7 + ie9.0 ):

 

I learned things from CSS. Therefore, the table layout will be improved.

 

Reprinted please indicate the source, original address: http://blog.csdn.net/morewindows/article/details/7102362

 

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.