Home > Backend Development > PHP Tutorial > PHP Access MySql Database Advanced AJAX Technology_PHP Tutorial

PHP Access MySql Database Advanced AJAX Technology_PHP Tutorial

WBOY
Release: 2016-07-13 17:47:54
Original
955 people have browsed it

Before reading this article, it is recommended to read "PHP Access MySql Database - Elementary" and "PHP Access MySql Database - Intermediate Smarty Technology".

In the previous article, we have developed a program that can read the database and display the data, and the program has achieved a good interface and logical separation. But this program does not support us to add, delete and modify the database. So add these features here. Every time data is added, deleted or modified, a request is sent to the background through AJAX, and the page display is adjusted based on the results returned by the background. This approach can reduce the load on the server.

The following will briefly introduce AJAX, and then give a complete example:

AJAX is a browser technology that is independent of web server software. It is not a new programming language, but a technology for creating better, faster, and more interactive web applications. Through AJAX, you can use JavaScript's XMLHttpRequest object to communicate directly with the server. This allows data to be exchanged 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 web page can request a small amount of information from the server instead of the entire page. The AJAX manual can be accessed at 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 then displaying it. It also supports AJAX addition, deletion and modification operations on the t_student table. In terms of interface functions, the odd and even rows of the table also change color as the mouse passes, making the program more beautiful.

The program is divided into 8 files, namely smarty2.php, smarty2.html, smarty2_head.php, smarty2.js, smarty2.css and the newly added insert.php, delete.php and update.php.

1. smarty2_head.php file

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

// 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');
?>
// 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

// 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); 
 
//个数  
$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; 
//表中内容  
$tpl_db_rows = array(); 
$sql = sprintf("select %s from %s", implode(",",$dbcolarray), DB_TABLENAME); 
$result = mysql_query($sql, $conn); 
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))//等价$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'); 
?> 
// 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);

//个数
$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;
//表中内容
$tpl_db_rows = array();
$sql = sprintf("select %s from %s", implode(",",$dbcolarray), DB_TABLENAME);
$result = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))//等价$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文件

 
 
 
 
 
 
{$smarty.const.DB_TABLENAME} 
 
 

表名:{$db_tablename}

 
 
 
{foreach $db_coltitle as $col} 
     
{/foreach} 
 
{foreach $db_rows as $dbrow} 
     
    {foreach $dbrow as $k=>$val} 
         
    {/foreach} 
      
     
{/foreach} 
当前记录数:     
{$col} 操作
{$val} 
         
         
   
 
 
 
 
 
 






{$smarty.const.DB_TABLENAME}


表名:{$db_tablename}




{foreach $db_coltitle as $col}
   
{/foreach}

{foreach $db_rows as $dbrow}
   
    {foreach $dbrow as $k=>$val}
       
    {/foreach}
 
   
{/foreach}
当前记录数:     
{$col} 操作
{$val}
  
  
 





4. smarty2.js file

Newly added row discoloration effect when the mouse passes over the table

//Find the row equal to the specified ID in the first column of the table
function SearchIdInTable(tablerow, findid)
{
var i;
var tablerownum = tablerow.length;
for (i = 1; i < tablerownum; i++)
If ($("#Table tr:eq(" + i + ") td:eq(0)").html() == findid)
                 return i;                                 Return -1;
}
//Use CSS to control the color of odd and even rows
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");},
function(){$(this).css("background-color", "#e6e6fa");}
);
$("#Table tr:even").hover(
Function(){$(this).css("background-color", "orange");},
function(){$(this).css("background-color", "#fff0fa");}
);
}
//Response to edit button
function editFun(id, name, age)
{
$("#editdiv").show();
$("#adddiv").hide();

$("#editdiv_id").val(id);
$("#editdiv_name").val(name);
$("#editdiv_age").val(age);
}
//Response to add button
function addFun()
{
$("#editdiv").hide();
$("#adddiv").show();
}
//Increase the number of records
function IncTableRowCount()
{
var tc = $("#tableRowCount");
​ tc.html(parseInt(tc.html()) + 1);
}
//Reduced number of records
function DecTableRowCount()
{
var tc = $("#tableRowCount");
​ tc.html(parseInt(tc.html()) - 1);
}
//Add a line
function addRowInTable(id, name, age)
{
//Add a new line
var appendstr = "";
appendstr += "" + id + "";
appendstr += "" + name + "";
appendstr += "" + age + "";
​ appendstr += "";
​ appendstr += "";
      appendstr += "";                          $("#Table").append(appendstr);
IncTableRowCount();
}
//Modify a certain line
function updataRowInTable(id, newname, newage)
{
var i = SearchIdInTable($("#Table tr"), id);
If (i != -1)
{
            $("#Table tr:eq(" + i + ") td:eq(1)").html(name != "" ? name : " ");
            $("#Table tr:eq(" + i + ") td:eq(2)").html(age != "" ? age : " ");
          $("#editdiv").hide();
}  
}
//Delete a certain line
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 and modify database functions to communicate with the server through AJAX
function insertFun()
{
var name = $("#adddiv_name").val();
var age = $("#adddiv_age").val();

If (name == "" || age == "")
{
alert("Please 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("Confirm deletion?"))
{
//submit to server
          $.post("delete.php", {id:id}, function(data){
If (data == "f")
                                                                  alert("delete date failed");
                                                                                                                                                                                                                          else                                                                                        deleteRowInTable(id);
                                                                                                                                              });
}  
}
function updateFun()
{
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();
});
//Find the row equal to the specified ID in the first column of the table
function SearchIdInTable(tablerow, findid)
{
var i;
var tablerownum = tablerow.length;
for (i = 1; i < tablerownum; i++)
if ($("#Table tr:eq(" + i + ") td:eq(0)").html() == findid)
Return i;
return -1;
}
//Use CSS to control the color of odd and even rows
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");},
function(){$(this).css("background-color", "#e6e6fa");}
);
$("#Table tr:even").hover(
function(){$(this).css("background-color", "orange");},
function(){$(this).css("background-color", "#fff0fa");}
);
}
//Response to edit button
function editFun(id, name, age)
{
$("#editdiv").show();
$("#adddiv").hide();

$("#editdiv_id").val(id);
$("#editdiv_name").val(name);
$("#editdiv_age").val(age);
}
//Response to add button
function addFun()
{
$("#editdiv").hide();
$("#adddiv").show();
}
//Increase the number of records
function IncTableRowCount()
{
var tc = $("#tableRowCount");
tc.html(parseInt(tc.html()) + 1);
}
//The number of records is reduced
function DecTableRowCount()
{
var tc = $("#tableRowCount");
tc.html(parseInt(tc.html()) - 1);
}
//Add a line
function addRowInTable(id, name, age)
{
//Add a new line
var appendstr = "";
​ appendstr += "" + id + "";
​ appendstr += "" + name + "";
appendstr += "" + age + "";
​ appendstr += "";
​ appendstr += "";
     appendstr += "";                                $("#Table").append(appendstr);
IncTableRowCount();
}
//Modify a certain line
function updataRowInTable(id, newname, newage)
{
var i = SearchIdInTable($("#Table tr"), id);
If (i != -1)
{
$("#Table tr:eq(" + i + ") td:eq(1)").html(name != "" ? name : " ");
            $("#Table tr:eq(" + i + ") td:eq(2)").html(age != "" ? age : " ");
​​​​ $("#editdiv").hide();
}
}
//Delete a certain line
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 and modify database functions to communicate with the server through AJAX
function insertFun()
{
var name = $("#adddiv_name").val();
var age = $("#adddiv_age").val();

if (name == "" || age == "")

{
alert("Please enter your name and age!");
Return ;
}

    //submit to server 返回插入数据的id
    $.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("确认删除?"))
 {
  //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文件

@charset "utf-8"; 
h1 

    color:Red; 
    text-align:center; 

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

 background-color:#7cfc00; 
}
6.新增加的insert.php

将数据插入数据库中,成功返回新插入数据的id号,失败返回"f"。

view plaincopy to clipboardprint? require_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); 
?> 
require_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.新增加的delete.php

根据id删除数据库中一行记录,成功返回"f",失败返回"t"。

view plaincopy to clipboardprint? require_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"; 
?> 
require_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.新增加的updata.php

根据id修改数据库中一行记录,成功返回"f",失败返回"t"。

  require_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"; 
?> 
require_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";
?>
程序运行结果如下(Win7 +IE9.0):

 

 

本人CSS学的太菜。所以表格的布局将就点了。

 

摘自 MoreWindows

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478475.htmlTechArticle阅读本文之前,推荐先参阅《PHP访问MySql数据库 初级篇》和《PHP访问MySql数据库 中级篇 Smarty技术》。 在前面的文章,我们已经开发了一个...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template