目录

一、php与mysql

二、Ajax


一、php与mysql

(一)操作语句

1.数据库连接如$conn = mysql_connect('localhost','root','123456');

2.mysql_query() 函数  该函数用于向 SQL 连接发送查询和命令

3.mysql_select_db() 函数选取数据库如mysql_select_db("cloud", $conn);

4.插入语句$result = mysql_query("INSERT INTO device_list (dev_name, os,network,ip,defalut_gateway,os_source,subnet_mask) VALUES('$dev_name','$os',' $network','$ip','$defalut_gateway','$os_source','$subnet_mask')");

不使用ajax的时候,纯html和php的简单交互实例

当用户点击上例中 HTML 表单中的提交按钮时,表单数据被发送到 "insert.php"。"insert.php" 文件连接数据库,并通过 $_POST 变量从表单取回值。然后,mysql_query() 函数执行 INSERT INTO 语句,一条新的记录会添加到数据库表中。

HTML:
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

php: 

<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

5.选取语句select

 $result 变量中存放由 mysql_query() 函数返回的数据。接下来,我们使用 mysql_fetch_array() 函数以数组的形式从记录集返回第一行。每个随后对 mysql_fetch_array() 函数的调用都会返回记录集中的下一行。 while 语句会循环记录集中的所有记录。为了输出每行的值,我们使用了 PHP 的 $row 变量 ($row['FirstName'] 和 $row['LastName'])。

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);
?>

 如果要是将返回的记录返回给前端页面的话

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

6. where / order by

(二)数据库

1.一般用到最多的就是VARCHAR(size)支持可变长度的字符串(可包含字母、数字以及特殊符号)在 size 参数中规定最大长度。

2.日期(在操作日志里面需要时间日期字段)

  • date(yyyy-mm-dd)
  • datetime(yyyy-mm-dd hh:mm:ss)
  • timestamp(yyyymmddhhmmss)
  • time(hh:mm:ss)

3.主键用于对表中的行进行唯一标识,每个主键值在表中必须是唯一的。此外,主键字段不能为空,这是由于数据库引擎需要一个值来对记录进行定位。 

二、Ajax

(一)与mysql交互的实例

数据库内容

mysql> select * from websites;
+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘宝       | https://www.taobao/   | 13    | CN      |
| 3  | 菜鸟教程 | http://www.runoob/    | 4689  | CN      |
| 4  | 微博       | http://weibo/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook/ | 3     | USA     |
+----+--------------+---------------------------+-------+---------+
5 rows in set (0.01 sec)

当用户在上面的下拉列表中选择某位用户时,会执行名为 "showSite()" 的函数。该函数由 "onchange" 事件触发:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob)</title> 
<script>
function showSite(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    } 
    if (window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 浏览器执行代码
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","getsite_mysql.php?q="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>
 
<form>
<select name="users" onchange="showSite(this.value)">
<option value="">选择一个网站:</option>
<option value="1">Google</option>
<option value="2">淘宝</option>
<option value="3">菜鸟教程</option>
<option value="4">微博</option>
<option value="5">Facebook</option>
</select>
</form>
<br>
<div id="txtHint"><b>网站信息显示在这里……</b></div>
 
</body>
</html>

showSite() 函数会执行以下步骤:

  • 检查是否有网站被选择
  • 创建 XMLHttpRequest 对象
  • 创建在服务器响应就绪时执行的函数
  • 向服务器上的文件发送请求
  • 请注意添加到 URL 末端的参数(q)(包含下拉列表的内容)

上面这段通过 JavaScript 调用的服务器页面是名为 "getsite_mysql.php" 的 PHP 文件。

"getsite_mysql.php" 中的源代码会运行一次针对 MySQL 数据库的查询,然后在 HTML 表格中返回结果:

<?php
$q = isset($_GET["q"]) ? intval($_GET["q"]) : '';
 
if(empty($q)) {
    echo '请选择一个网站';
    exit;
}
 
$con = mysqli_connect('localhost','root','123456');
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}
// 选择数据库
mysqli_select_db($con,"test");
// 设置编码,防止中文乱码
mysqli_set_charset($con, "utf8");
 
$sql="SELECT * FROM Websites WHERE id = '".$q."'";
 
$result = mysqli_query($con,$sql);
 
echo "<table border='1'>
<tr>
<th>ID</th>
<th>网站名</th>
<th>网站 URL</th>
<th>Alexa 排名</th>
<th>国家</th>
</tr>";
 
while($row = mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['url'] . "</td>";
    echo "<td>" . $row['alexa'] . "</td>";
    echo "<td>" . $row['country'] . "</td>";
    echo "</tr>";
}
echo "</table>";
 
mysqli_close($con);
?>

解释:当查询从 JavaScript 发送到 PHP 文件时,将发生:

  1. PHP 打开一个到 MySQL 数据库的连接
  2. 找到选中的用户
  3. 创建 HTML 表格,填充数据,并发送回 "txtHint" 占位符

(二) 与mysql交互的实例2

1.1、删除操作

前端ajax

$.ajax({
     url:'./data2.php?action=del',
     type:'post',
     data:{'dev_name':data.dev_name},//向服务端发送删除的id
     success:function(result){
          layer.close(index);
          layer.msg("删除成功",{  time:1000,icon:1}); 
          window.parent.location.reload();
     },
     error:function(){
          layer.msg("删除失败",{icon:5});
     },
});

后端php文件

 function del($conn,$stu_num1){
	  $result = mysql_query("delete  FROM device_list where dev_name ='$stu_num1' ");     
      if($result){
         echo json_encode(array(
            "code" => 1,
            "msg" => "success",
            "count" =>  $c,
            "data" => array()
         ));
       }
 }

1.2 批量删除操作

layer.confirm('确定要批量删除吗?',   function(index){
                      var data = checkStatus.data;   
                      var dataObj = [];
                      data.forEach((item,i) => {
                      dataObj.push(item.dev_name)
                        });
                      var dataArray=[];
                      for (var i in dataObj)
                      {
                        dataArray.push(dataObj[i]);
                      }  

                      $.ajax({
                        url:'./data2.php?action=pdel',
                        type:'post',
                        data:{'dataArray':dataObj},//向服务端发送删除的id
                        success:function(result){
                    
                        // if(result==1){
                        // obj.del(); //删除对应行(tr)的DOM结构,并更新缓存
                        layer.close(index);
                        // console.log(index);
                        layer.msg("删除成功",{  time:1000,icon:1});
                      
                        window.parent.location.reload();
                          },
                        
                        error:function(){
                              layer.msg("删除失败",{icon:5});
                        },                 
                      });

                      layer.close(index); 
                      },
                      
                      function() {
                        layer.msg('取消删除成功', {
                          time: 1000 //1s后自动关闭
                        });
                      }
function pdel($conn,$dataArray){
     foreach ( $dataArray  as  $v ) {
		 $result = mysql_query("delete  FROM device_list where dev_name ='$v' ");    
      }

      if($result){
          echo json_encode(array(
             "code" => 1,
             "msg" => "success",
             "count" =>  $c,
             "data" => array()
          ));
       }
 }

 

2、增加操作

将之前隐藏的saveOrupdateDiv表单显示出来

function openAddUser() {
        mainIndex=layer.open({
          type:1,
          title:'添加设备',
          content:$("#saveOrupdateDiv"),
          // area:['100px' ],
          success(){         
            // 清空表单数据。即修改用户时数据会显示在这里,因此要去除
            $("#dataForm")[0].reset(); //转换为js jquery中没有submit方醃
           url = './data2.php?action=add';       
        }
        })
    }

当点击提交的时候,开始进行ajax与后端交换数据

form.on('submit(doSubmit1)', function(data){
        // 序列化表单数据
        var params = $('#dataForm1').serialize();
        $.ajax({
            url:'./data2.php?action=update',
            type:'post',
            data:params,//向服务端发送删除的id
            success:function(result){            
                layer.msg("修改成功",{  time:1000,icon:1});         
                window.parent.location.reload();
            },
            error:function(){
                layer.msg("修改失败!",{icon:5});
            },
                  
        });

        layer.close(mainIndex);  //mainIndex对应前面的layer.open()
    });

 后端php与mysql交互内容

function add($conn){
    $clean = array();
    mysql_select_db("cloud", $conn);
    mysql_query("SET NAMES utf8");
    $dev_name = isset($_POST['dev_name'])? $_POST['dev_name'] :'null'; 
    $os = isset($_POST['os'])? $_POST['os'] :'null'; 
    $network = isset($_POST['network'])? $_POST['network'] :'null'; 
    $ip = isset($_POST['ip'])? $_POST['ip'] :'null'; 
    $defalut_gateway = isset($_POST['defalut_gateway'])? $_POST['defalut_gateway'] :'null'; 
    $os_source = isset($_POST['os_source'])? $_POST['os_source'] :'null'; 
    $subnet_mask = isset($_POST['subnet_mask'])? $_POST['subnet_mask'] :'null'; 


    $result = mysql_query("SELECT * FROM device_list where dev_name ='$dev_name' ");
    $rows = mysql_num_rows($result);
    if($rows<1)
    {
         $password='123456';
		 $result = mysql_query("INSERT INTO device_list (dev_name, os,network,ip,defalut_gateway,os_source,subnet_mask) VALUES('$dev_name','$os',' $network','$ip','$defalut_gateway','$os_source','$subnet_mask')");
    }
   if($rows<1 ){
    echo json_encode(array(
      "code" => 1,
      "msg" => "success",
      "count" =>  $c,
      "data" => array()
    ));
  }
 }

 3.修改操作

function openUpdateUser(data) {
      mainIndex = layer.open({
        type:1,
        title:'修改设备',
        closeBtn: 1,
        content:$("#saveOrupdateDiv1"),
      
        success: function() {
          form.val('dataForm',{
            dev_name:data[0].dev_name,
            os:data[0].os,
            network:data[0]work,
            ip:data[0].ip,
            defalut_gateway:data[0].defalut_gateway,
            os_source:data[0].os_source,
            subnet_mask:data[0].subnet_mask,
          })
          url = './data2.php?action=update';
        }
      })
    }
function upd($conn){
    $clean = array();
    $dev_name = isset($_POST['dev_name'])? $_POST['dev_name'] :''; 
    $os = isset($_POST['os'])? $_POST['os'] :''; 
    $network = isset($_POST['network'])? $_POST['network'] :''; 
    $ip = isset($_POST['ip'])? $_POST['ip'] :''; 
    $defalut_gateway = isset($_POST['defalut_gateway'])? $_POST['defalut_gateway'] :''; 
    $os_source = isset($_POST['os_source'])? $_POST['os_source'] :''; 
    $subnet_mask = isset($_POST['subnet_mask'])? $_POST['subnet_mask'] :'';    
    if ($os != ''){
		   $result1 = mysql_query("UPDATE device_list SET os='$os' where dev_name= '$dev_name' ");
        }
        if ( $network != ''){
		 $result2 = mysql_query("UPDATE device_list SET network='$network' where dev_name= '$dev_name' ");
        }
        if ( $ip!= ''){
		  $result3 = mysql_query("UPDATE device_list SET ip='$ip' where dev_name='$dev_name' ");
  
        }
         if ( $defalut_gateway!= ''){
         $result4 = mysql_query("UPDATE device_list SET defalut_gateway='$defalut_gateway' where dev_name='$dev_name' ");
        }   
        
        if ( $os_source!= ''){
            $result4 = mysql_query("UPDATE device_list SET os_source='$os_source' where dev_name='$dev_name' ");
    
        }
        if ( $subnet_mask!= ''){
            $result6 = mysql_query("UPDATE device_list SET subnet_mask='$subnet_mask' where dev_name='$dev_name' ");
    
        }    
   if($result1||$result2||$result3||$result4||$result5||$result6){
    echo json_encode(array(
      "code" => 1,
      "msg" => "success",
      "count" =>  $c,
      "data" => array()
    ));
  }                    
 }

更多推荐

php mysql ajax