Table of Contents
表名:{$db_tablename}
Home php教程 php手册 PHP访问MySql数据库 高级篇 AJAX技术

PHP访问MySql数据库 高级篇 AJAX技术

Jun 13, 2016 am 10:46 AM
ajax mysql php technology recommend database access read advanced

阅读本文之前,推荐先参阅《PHP访问MySql数据库 初级篇》和《PHP访问MySql数据库 中级篇 Smarty技术》。

在前面的文章,我们已经开发了一个能够读取数据库并显示数据的程序,且程序达到了良好的界面与逻辑分离。但是这个程序并不能支持我们对数据库进行增加、删除和修改操作。因此在这里增加这些功能。每次增加删除或修改数据时,通过AJAX方式向后台发送请求,再根据后台的返回结果调整页面显示。这种方法可以减轻服务器的负担。

 

下面先简单的介绍下AJAX,然后给出完整的示例:

AJAX 是一种独立于 Web 服务器软件的浏览器技术。它不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的 Web 应用程序的技术。通过 AJAX方式,可使用 JavaScript 的XMLHttpRequest 对象来直接与服务器进行通信。这样便可以在不重载页面的情况与 Web 服务器交换数据。同时AJAX 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求),这样就可使网页从服务器请求少量的信息,而不是整个页面。AJAX手册可以访问http://api.jquery.com/category/ajax/

 

下面是本系列中功能最为全面的程序——从test数据库的t_student表中读取数据然后显示,同时支持对t_student表进行AJAX方式的增加、删除和修改操作。在界面功能上也有表格的奇偶行变色及鼠标经过变色,使得程序更加的美观。

程序共分为8个文件,分别为smarty2.php、smarty2.html、smarty2_head.php、smarty2.js和smarty2.css及新增加的insert.php、delete.php及updata.php。

1.smarty2_head.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'); 
?> 
// 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文件

// 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文件

新增加了表格的鼠标经过行变色效果

//在表格的第一列中查找等于指定ID的行  
function SearchIdInTable(tablerow, findid) 

    var i; 
    var tablerownum = tablerow.length; 
    for (i = 1; i         if ($("#Table tr:eq(" + i + ") td:eq(0)").html() == findid) 
            return i; 
    return -1; 

//用CSS控制奇偶行的颜色  
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");}      
); 

//响应edit按钮  
function editFun(id, name, age) 

    $("#editdiv").show(); 
    $("#adddiv").hide(); 
 
    $("#editdiv_id").val(id); 
    $("#editdiv_name").val(name); 
    $("#editdiv_age").val(age); 

//响应add按钮  
function addFun() 

    $("#editdiv").hide(); 
    $("#adddiv").show();     

//记录条数增加  
function IncTableRowCount() 

    var tc = $("#tableRowCount"); 
    tc.html(parseInt(tc.html()) + 1); 

//记录条数减少  
function DecTableRowCount() 

    var tc = $("#tableRowCount"); 
    tc.html(parseInt(tc.html()) - 1); 

//增加一行  
function addRowInTable(id, name, age) 

    //新增加一行  
    var appendstr = "

"; 
    appendstr += "" + id + ""; 
    appendstr += "" + name + ""; 
    appendstr += "" + age + ""; 
    appendstr += " "; 
    appendstr += " "; 
    appendstr += "";          
    $("#Table").append(appendstr); 
    IncTableRowCount(); 

//修改某一行  
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(); 
    } 

//删除某一行  
function deleteRowInTable(id) 

    var i = SearchIdInTable($("#Table tr"), id); 
    if (i != -1) 
    {    
        //删除表格中该行  
        $("#Table tr:eq(" + i + ")").remove(); 
        SetTableRowColor(); 
        DecTableRowCount(); 
    } 

//增加删除修改数据库函数 通过AJAX与服务器通信  
function insertFun() 

    var name = $("#adddiv_name").val(); 
    var age = $("#adddiv_age").val(); 
 
    if (name == "" || age == "") 
    { 
        alert("请输入名字和年龄!"); 
        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(); 
});   
//在表格的第一列中查找等于指定ID的行
function SearchIdInTable(tablerow, findid)
{
    var i;
    var tablerownum = tablerow.length;
 for (i = 1; i   if ($("#Table tr:eq(" + i + ") td:eq(0)").html() == findid)
   return i;
 return -1;
}
//用CSS控制奇偶行的颜色
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");}  
);
}
//响应edit按钮
function editFun(id, name, age)
{
    $("#editdiv").show();
    $("#adddiv").hide();

    $("#editdiv_id").val(id);
    $("#editdiv_name").val(name);
    $("#editdiv_age").val(age);
}
//响应add按钮
function addFun()
{
    $("#editdiv").hide();
    $("#adddiv").show();   
}
//记录条数增加
function IncTableRowCount()
{
 var tc = $("#tableRowCount");
 tc.html(parseInt(tc.html()) + 1);
}
//记录条数减少
function DecTableRowCount()
{
 var tc = $("#tableRowCount");
 tc.html(parseInt(tc.html()) - 1);
}
//增加一行
function addRowInTable(id, name, age)
{
    //新增加一行
    var appendstr = "

";
    appendstr += "" + id + "";
    appendstr += "" + name + "";
    appendstr += "" + age + "";
    appendstr += " ";
    appendstr += " ";
    appendstr += "";        
    $("#Table").append(appendstr);
    IncTableRowCount();
}
//修改某一行
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();
    }
}
//删除某一行
function deleteRowInTable(id)
{
 var i = SearchIdInTable($("#Table tr"), id);
 if (i != -1)
 { 
  //删除表格中该行
  $("#Table tr:eq(" + i + ")").remove();
  SetTableRowColor();
  DecTableRowCount();
 }
}
//增加删除修改数据库函数 通过AJAX与服务器通信
function insertFun()
{
    var name = $("#adddiv_name").val();
    var age = $("#adddiv_age").val();

    if (name == "" || age == "")
    {
     alert("请输入名字和年龄!");
     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
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)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

See all articles