欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询

程序员文章站 2022-04-04 11:13:21
...

成果展示

ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询

ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询
ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询
ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询

ajax与数据库的应用之注册,登录,建表,删除,修改,模糊查询
第一步
公共导入数据库部分php

<?php
//防止字符乱码
@header("Content-Type:text/html;charset=utf-8");
// 连接mysql  mysqli_connect("数据库ip/主机","用户名","密码");
$conn = mysqli_connect("localhost:3306", "root", "root");
// 链接数据库
mysqli_select_db($conn, "1911");
// 从数据库取数据 的时候 把字符集设置为 utf-8
mysqli_query($conn, "set names utf8");
//  向数据库中存数据的时候 把字符集设置为 utf-8
mysqli_query($conn, "set character set utf-8");

第二步
判断用户名,电话,邮箱不可重复的公共部分php

<?php

//判断 用户名 是否存在
function isExistUser($user)
{
    //在函数内的 $conn为局部变量,要将其变为全局变量
    global $conn;
    //查询输入用户名mysqli_query
    $search = "select * from `userinfo` where user='$user'";
    $result = mysqli_query($conn, $search);
    // 解析查询语句结果mysqli_fetch_array $result 有数据返回对应的数据信息  没有返回 null
    $iteam = mysqli_fetch_array($result);
    //有对应的用户名时$iteam则为true
    if ($iteam) {
        return true; //存在
    } else {
        return false;
    }
}
//判断查询语句mysqli_query($conn, $search)是否有返回信息,也可以用$result->num_row
//echo $result->num_rows;    $result->num_rows 取对象中数据的写法
// >0  存在  ==0 不存在


//判断 手机号 是否存在
function isExistPhone($phone)
{
    global $conn;
    $search = "select * from `userinfo` where user='$phone'";
    $result = mysqli_query($conn, $search);
    $iteam = mysqli_fetch_array($result);
    if ($iteam) {
        return true; //存在
    } else {
        return false;
    }
}

//判断 邮箱 是否存在
function isExistEmail($email)
{
    global $conn;
    $search = "select * from `userinfo` where user='$email'";
    $result = mysqli_query($conn, $search);
    $iteam = mysqli_fetch_array($result);
    if ($iteam) {
        return true; //存在
    } else {
        return false;
    }
}

第三步
注册php

<?php
@header("Content-Type:text/html;charset=utf-8");
//连接其他PHP文件,注意顺序,连接数据库的PHP文件必须放在前面
require_once "conn.php";
require_once "common.php";

//echo mysqli_select_db($conn, "1911");  //判断数据库成功连上,1911是我数据库的名称

//如果连接上
if (mysqli_select_db($conn, "1911")) {
    //获取输入的user,pwd,phone,email
    $user = $_GET["user"];
    $pwd = $_GET["pwd"];
    $phone = $_GET["phone"];
    $email = $_GET["email"];

    $msg = array();
    //判断用户名,手机号,邮箱是否存在,如果存在,则返回对应信息,否则插入数据
    if (isExistUser($user)) {
        $msg["status"] = false; //存在
        $msg["msg"] = "用户名已存在";
    } else if (isExistPhone($phone)) {
        $msg["status"] = false; //存在
        $msg["msg"] = "手机号已存在";
    } else if (isExistEmail($email)) {
        $msg["status"] = false; //存在
        $msg["msg"] = "邮箱已存在";
    } else {
        //插入数据
        $insert = "insert into `userinfo`(user,pwd,phone,email) values('$user','$pwd','$phone','$email')";
        mysqli_query($conn, $insert);
        //返回值为受影响的行数mysqli_affected_rows
        $row = mysqli_affected_rows($conn);
        if ($row > 0) {
            //>0   成功   $row   返回对应的受影响行数
            $msg["status"] = true;
            $msg["msg"] = "success!";
        } else if ($row == 0) {
            // ==0  (增删改失败) 数据没有影响
            $msg["status"] = false;
            $msg["msg"] = "fail!";
        } else {
            // -1   失败   sql语句有问题
            $msg["status"] = false;
            $msg["msg"] = "sql error!";
        }
    }
    echo json_encode($msg);
    mysqli_close($conn);   //关闭数据库
} else {
    echo "数据库连接失败!!";
}

第四步
注册html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <style>
  * {
   padding: 0;
   margin: 0;
  }

  p {
   margin-top: 10px;
  }

  P:last-of-type button {
   margin-left: 50px;
  }

  label {
   display: inline-block;
   width: 80px;
   text-align: right;
   padding-right: 10px;
  }

  .right {
   font-size: 14px;
   color: blue;
  }

  .err {
   font-size: 14px;
   color: red;
  }
 </style>
</head>

<body>
 <p><label for="user">用户名</label><input id="user" type="text"> <span id="user_span"></span> </p>
 <p><label for="pwd">密码</label><input id="pwd" type="text"> <span id="pwd_span"></span> </p>
 <p><label for="repwd">确认密码</label><input id="repwd" type="password"> <span id="repwd_span"></span> </p>
 <p><label for="phone">手机号</label><input id="phone" type="text"> <span id="phone_span"></span> </p>
 <p><label for="email">邮箱</label><input id="email" type="text"> <span id="email_span"></span> </p>
 <p><label for="user">验证码</label><input id="code" type="text"> <span id="randCode">1356</span><span id="code_span"></span> </p>
 <p><button id="btn">注册</button></p>
</body>
<script>
//用户名
 var userInp = document.getElementById("user");
 var userSpan = document.getElementById("user_span");
//密码
 var pwdInp = document.getElementById("pwd");
 var pwdSpan = document.getElementById("pwd_span");
//确认密码
 var repwdInp = document.getElementById("repwd");
 var repwdSpan = document.getElementById("repwd_span");
//验证码
 var codeInp = document.getElementById("code");
 var codeSpan = document.getElementById("code_span");
//手机号
 var phoneInp = document.getElementById("phone");
 var phoneSpan = document.getElementById("phone_span");
//邮箱
 var emailInp = document.getElementById("email");
 var emailSpan = document.getElementById("email_span");
//随机验证码
 var randCode = document.getElementById("randCode");
//注册按钮
 var btn = document.getElementById("btn");

//调用createCode()生成随机验证码
 randCode.innerHTML = createCode();

//点击随机验证码,更换验证码
 randCode.onclick = function () {
  randCode.innerHTML = createCode();
 }


 /* 
 用户名:
 名字只能包含数字、字母和下划线,$
 数字不可以开头
 长度不低于6,不长于12  
 */
 //输入或失焦时调用判断用户名函数
 userInp.oninput = userInp.onblur = judgeUser;
 function judgeUser() {
     //获取输入的用户名
  var user = userInp.value;
      //设置flag变量作为函数返回值
  var flag = false;
  if (user) {
   var lenReg = /^.{6,12}$/;   //长度验证
   var startReg = /^[^0-9]/;   //首字符验证
   var userReg = /^[a-zA-Z_$\u4e00-\u9fa5][0-9a-zA-Z_$\u4e00-\u9fa5]{5,11}$/; //所有字符验证
   if (lenReg.test(user) == true) {
    //长度正确
    if (startReg.test(user) == true) {
     //首字母正确
     if (userReg.test(user) == true) {
      //内容正确
      userSpan.innerHTML = "√";
      userSpan.className = "right";
      flag = true; //函数返回值为true
     } else {
      userSpan.innerHTML = "* 用户名还有非法字符";
      userSpan.className = "err";
     }

    } else {
     userSpan.innerHTML = "* 用户名不能以数字开头";
     userSpan.className = "err";
    }

   } else {
    userSpan.innerHTML = "* 用户名长度需要在6-12位之间";
    userSpan.className = "err";
   }

  } else {
   userSpan.innerHTML = "* 请输入用户名";
   userSpan.className = "err";
  }
  return flag;
 }


 //密码由数字,字母,下划线,$ 组成 
 //长度6-20 位 
 pwdInp.oninput = pwdInp.onblur = judegPwd;
 function judegPwd() {
  var pwd = pwdInp.value;
  var lenReg = /^.{6,20}$/;     //长度验证
  var pwdReg = /^[\w$]{6,20}$/; //所有字符验证
  var flag = false;
  if (pwd) {
   if (lenReg.test(pwd) == true) {
    //长度正确
    if (pwdReg.test(pwd) == true) {
     //所有字符正确
     flag = true;

     //判断密码强度
     var numReg = /[0-9]/;
     var smallReg = /[a-z]/;
     var bigReg = /[A-Z]/;
     // 1   a  A   
     // 1a  1A   aA
     // a1  A1   Aa

     var isExistNum = false;
     var isExistSmall = false;
     var isExistBig = false;

     //存在数字
     if (numReg.test(pwd)) {
      isExistNum = true;
     }

     //存在小写字母
     if (smallReg.test(pwd)) {
      isExistSmall = true;
     }

     //存在大写字母
     if (bigReg.test(pwd)) {
      isExistBig = true;
     }

     //查看存在几种字符
     var sum = isExistNum + isExistSmall + isExistBig;
     //console.log(sum);

     //存在几种字符强度就为多少
     pwdSpan.innerHTML = "√ 强度:" + sum;
     pwdSpan.className = "right";

    } else {
     pwdSpan.innerHTML = "* 密码还有非法字符";
     pwdSpan.className = "err";
    }

   } else {
    pwdSpan.innerHTML = "* 密码长度需要在6-12位之间";
    pwdSpan.className = "err";
   }

  } else {
   pwdSpan.innerHTML = "* 请输入密码";
   pwdSpan.className = "err";
  }

  return flag;

 }

 //判断密码是否一致
 repwdInp.oninput = repwdInp.onblur = judgeRePwd;
 function judgeRePwd() {

  var repwd = repwdInp.value;
  var pwd = pwdInp.value;
  var flag = false;

  if (repwd) {
   if (repwd == pwd) {
    repwdSpan.innerHTML = "√";
    repwdSpan.className = "right";
    flag = true;
   }

   else {
    repwdSpan.innerHTML = "* 两次密码输入不一致;";
    repwdSpan.className = "err";
   }

  }

  else {
   repwdSpan.innerHTML = "* 请输入密码";
   repwdSpan.className = "err";
  }

  return flag;
 }

//判断验证码是否一致
 codeInp.oninput = codeInp.onblur = judgeCode;
 function judgeCode() {
  var code = codeInp.value;
  var judgeCode = randCode.innerHTML;

  var codeReg = new RegExp(judgeCode, "ig");
  var flag = false;

  if (code) {

   if (codeReg.test(code)) {
    //密码与验证码一致
    codeSpan.innerHTML = "√";
    codeSpan.className = "right";
    flag = true;
   } else {
    codeSpan.innerHTML = "×";
    codeSpan.className = "err";
   }

  } else {
   codeSpan.innerHTML = "* 请输入验证码";
   codeSpan.className = "err";
  }

  return flag;
 }


//判断手机号是否输入正确
 phoneInp.oninput = phoneInp.onblur = judgePhone;
 function judgePhone() {
  var phone = phoneInp.value;
  var phoneReg = /^1[3456789]\d{9}$/;
  var flag = false;

  if (phone) {

   if (phoneReg.test(phone)) {
    phoneSpan.innerHTML = "√";
    phoneSpan.className = "right";
    flag = true;
   } 
   else {
    phoneSpan.innerHTML = "×  请输入正确的手机号";
    phoneSpan.className = "err";
   }

  } else {
   phoneSpan.innerHTML = "* 请输入手机号";
   phoneSpan.className = "err";
  }

  return flag;
 }


 // 邮箱6~18个字符,可使用字母、数字、下划线,需以字母开头
 // aaa@qq.com      (.com  .cn  .edu)  
 emailInp.oninput = emailInp.onblur = judgeEmail;
 function judgeEmail() {
  var email = emailInp.value;
  var startReg = /^[a-zA-Z]/;   //判断是否以首字母开始
  var emailReg = /^[a-zA-Z]\w{5,17}@[0-9a-zA-Z]{2,}(\.com|\.cn|\.edu|\.net)+$/
  var flag = false;
  if (email) {

   if (startReg.test(email)) {

    if (emailReg.test(email)) {
     emailSpan.innerHTML = "√";
     emailSpan.className = "right";
     flag = true;
    } else {
     emailSpan.innerHTML = "×  请输入正确的邮箱";
     emailSpan.className = "err";
    }
   } else {
    emailSpan.innerHTML = "* 邮箱需以字母开头";
    emailSpan.className = "err";
   }

  } else {
   emailSpan.innerHTML = "* 请输入邮箱";
   emailSpan.className = "err";
  }
  return flag;
 }

 //不连数据库时的普通样式
 // btn.onclick = function () {
 //     if (judgeUser() && judegPwd() && judgeRePwd() && judgePhone() && judgeEmail() && judgeCode()) {
 //         alert("注册成功!");
 //     }
 // }

//使用ajax连接数据库
  btn.onclick = function () {
  //先判断输入是否满足条件
  var userFlag = judgeUser();
  var pwdFlag = judegPwd();
  var rePwdFlag = judgeRePwd();
  var phoneFlag = judgePhone();
  var emailFlag = judgeEmail();
  var codeFlag = judgeCode();
  //若全部满足条件,用ajax连接数据库
  if (userFlag && pwdFlag && rePwdFlag && phoneFlag && emailFlag && codeFlag) {
   //获取用户所输入的信息
   var user = userInp.value,
    pwd = pwdInp.value,
    phone = phoneInp.value,
    email = emailInp.value;

  //创建http请求对象
   var req = new XMLHttpRequest();

   // req.open("get", "../php/get.php?user=" + user + "&pwd=" + pwd + "&phone=" + phone + "&email=" + email, true);

   //传入用户所输入的信息
   req.open("get", `./register.php?user=${user}&pwd=${pwd}&phone=${phone}&email=${email}`, true);
   //创建http请求对象
   req.send();
  // onreadystatechange  请求状态改变时触发该函数
   req.onreadystatechange = function () {
       //req.readyState == 4 && req.status == 200前端/后端交互完成
    if (req.readyState == 4 && req.status == 200) {
     //console.log(req.responseText);
     //得到数据库传输结果
     var result = JSON.parse(req.responseText);
     if (result.status) {
      alert("注册成功");
     } else {
      alert(result.msg);
     }
    }
   }
  }
 }


//随机生成验证码
 function createCode() {

  var codeStr = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
  var str = "";
  for (var i = 0; i < 4; i++) {
      //随机生成4个随机字符
   var index = Math.round(Math.random() * (codeStr.length - 1));
   var char = codeStr.charAt(index);
   str += char;
  }
  return str;
 }

</script>

</html>

第五步
登录php

<?php
@header("Content-Type:text/html;charset=utf-8");
//连接其他PHP文件
require_once "conn.php";

//获取地址栏中输入的count,pwd
$count = $_GET["count"];
$pwd = $_GET["pwd"];

if (mysqli_select_db($conn, "1911")) {
    //查询语句,判断用户所输入的用户名,电话,邮箱是否有一个一致
    $search ="select * from `userinfo` where user='$count' or phone = '$count' or email='$count'";
    $result = mysqli_query($conn, $search);
    // 解析查询语句结果mysqli_fetch_array $result 有数据返回对应的数据信息  没有返回 null
    $item = mysqli_fetch_array($result);
    $msg = array();
    //如果存在一致
    if ($item) {
        //判断密码是否一致
        $repwd = $item["pwd"];
        if ($pwd == $repwd) {
            $msg["status"] = true;
            $msg["msg"] = "success!";
            $msg["user"] = $item["user"];
            $msg["userId"] = $item["id"];
        } else {
            $msg["status"] = false;
            $msg["msg"] = "密码错误";
        }
    } else {
        $msg["status"] = false;
        $msg["msg"] = "该用户不存在";
    }
    echo json_encode($msg);
} else {
    echo "数据库连接失败";
}

第六步
登录html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="./cookie.js"></script>


 <style>
  * {
   padding: 0;
   margin: 0;
  }

  p {
   margin-top: 10px;
  }

  P:last-of-type button {
   margin-left: 50px;
  }

  label {
   display: inline-block;
   width: 80px;
   text-align: right;
   padding-right: 10px;
  }

  .right {
   font-size: 14px;
   color: blue;
  }

  .err {
   font-size: 14px;
   color: red;
  }
 </style>
</head>

<body>
 <p><label for="user">用户名</label><input id="user" type="text"> <span id="user_span"></span> </p>
 <p><label for="pwd">密码</label><input id="pwd" type="text"> <span id="pwd_span"></span> </p>
 <p><input class="isRem" type="checkbox">是否记住密码?</p>
 <p><button id="btn">登录</button></p>
</body>
<script>
//用户名/手机号/邮箱
 var userInp = document.getElementById("user");
 var userSpan = document.getElementById("user_span");
//密码
 var pwdInp = document.getElementById("pwd");
 var pwdSpan = document.getElementById("pwd_span");
//是否记住密码
 var isRem = document.getElementsByClassName("isRem")[0];
//登录按钮
 var btn = document.getElementById("btn");

 btn.onclick = function () {
     //获取用户输入的值
  var count = userInp.value;
  var pwd = pwdInp.value;
  //如果用户已输入全部信息,通过ajax连接数据库
  if (count && pwd) {
      //创建http请求对象
   var req = new XMLHttpRequest();
     //传入用户所输入的信息
   req.open("get", "./login.php?count=" + count + "&pwd=" + pwd, true);
     //创建http请求对象
   req.send();
   
   //req.onload = function () {} 等价于 req.onreadystatechange=function(){
   //if(req.readyState==4&&req.status==200){}
   //}
   
   req.onload = function () {
    console.log(req.responseText);
    var result = JSON.parse(req.responseText);
    //如果该用户已注册
    if (result.status) {
        //如果选中记住密码
     if (isRem.checked) {
         //设置cookie加设置过期时间
      setCookie("log_user", result.user, 7);
      setCookie("log_id", result.userId, 7);
     } else {
         //未选中记住密码时,浏览器会话结束时不保存用户登录信息
      setCookie("log_user", result.user);
      setCookie("log_id", result.userId);
     }
     //登录成功后开始跳转页面
     location.href="./table.html";
    } else {
        //未注册时返回错误信息
     alert(result.msg);
    }
   }
  }
 }


</script>

</html>

第七步
主页面(建表,删除,修改,查询)html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <style>
  * {
   padding: 0;
   margin: 0;
  }

  input {
   outline: none;
  }

  a {
   color: inherit;
   text-decoration: none;
  }

  li {
   list-style: none;
  }

  .wrapBox {
   width: 1080px;
   min-height: 500px;
   background-color: #6ff;
   margin: 50px auto;
  }

  .wrapBox .searchBox {
   display: flex;
  }

  .wrapBox .searchBox .searchCon {
   flex: 1;
  }

  .wrapBox .searchBox .searchBtn {
   width: 80px;
   height: 45px;
  }

  table,
  thead,
  tbody {
   width: 800px;
   border: 1px solid #000;
   margin-left: 140px;
   margin-top: 40px;
   position: relative;
  }

  tr {
   width: 800px;
   height: 40px;
   border: 1px solid #000;
  }

  td {
   text-align: center;
   width: 200px;
   height: 40px;
   border: 1px solid #000;
  }

  .shadow {
   width: 100%;
   height: 100%;
   position: fixed;
   top: 0;
   left: 0;
   display: none;
   background: rgba(163, 169, 170, .8);
  }

  .shadowcontent {
   width: 835px;
   height: 300px;
   margin-left: 200px;
   background: rgb(73, 184, 204);
  }

  .shadowcontent h2 {
   margin-top: 100px;
  }

  .shadowcontent input {
   background: rgb(73, 184, 204);
   width: 202px;
   height: 42px;
   font-size: 20px;
  }

  .shadowcontent table,
  .shadowcontent thead,
  .shadowcontent tbody {
   width: 800px;
   border: 1px solid #000;
   margin-left: 0px;
  }

  .submit {
   width: 100px;
   height: 40px;
   text-align: center;
   line-height: 40px;
   background: rgb(119, 197, 193);
   margin-left: 700px;
   margin-top: 40px;
  }
 tbody p{
  position: absolute;;
  left: 0;
  top:80px;
  width: 800px;
  height: 40px;
  text-align: center;
 }
 </style>
</head>

<body>
 <li id="ttbar-login" class="shortcut_btn fore1 dropdown" clstag="h|keycount|head|topbar_02">
  <a href="./login.html" class="link-login">你好,请登录</a>&nbsp;&nbsp;
  <a href="./register.html" class="link-regist style-red">免费注册</a>
 </li>

 <div class="wrapBox">
  <div class="searchBox">
   <input class="searchCon" type="text" name="" id="">
   <input class="searchBtn" onclick="cha()" type="button" value="搜索">
  </div>

  <table cellspacing="0" ;cellpadding="0">
   <thead>
    <tr>
     <td>编号</td>
     <td>用户名</td>
     <td>密码</td>
     <td>手机号</td>
     <td>邮箱</td>
     <td><a href="javascript:;">编辑</a></td>
     <td><a href="javascript:;">删除</a></td>
    </tr>
   </thead>
   <tbody>

   </tbody>
  </table>

 </div>


 <div class="shadow">
  <div class="shadowcontent">
   <h2>请修改以下对应数据</h2>
   <table cellspacing="0" ;cellpadding="0">
    <thead>
     <tr>
      <td>用户名</td>
      <td>密码</td>
      <td>手机号</td>
      <td>邮箱</td>
     </tr>
    </thead>
    <tr>
     <td><input class="user" type="text"></td>
     <td><input class="pwd" type="text"></td>
     <td><input class="phone" type="text"></td>
     <td><input class="email" type="text"></td>
    </tr>
    <tbody>
   </table>
   <button class="submit">提交</button>
  </div>
 </div>
</body>
<script src="./cookie.js"></script>
<script>

 var ttbarLogin = document.querySelector("#ttbar-login");
 var tbodys = document.querySelector("tbody");
 var shadow = document.getElementsByClassName("shadow")[0];
 var submit = document.getElementsByClassName("submit")[0];
 var userInput = document.getElementsByClassName("user")[0];
 var pwdInput = document.getElementsByClassName("pwd")[0];
 var phoneInput = document.getElementsByClassName("phone")[0];
 var emailInput = document.getElementsByClassName("email")[0];

 var searchCon = document.querySelector(".searchCon");
 var searchBtn = document.querySelector(".searchBtn");
 
 var cookie = document.cookie;
 //判断是否有用户登录
 if (cookie) {
  var log_user = getCookie("log_user");
  if (log_user) {
   ttbarLogin.innerHTML = ` 
            <a  class="link-login">欢迎您,${log_user}</a>&nbsp;&nbsp;
            <a  href="./login.html" class="exit" onclick="exit()">退出登录</a>`;
  }
 }

//填表刷新数据
 loadList()

 //填表
 function loadList() {
     
  var req = new XMLHttpRequest();
  req.open('get', `./table.php`, true);
  req.send();
  req.onreadystatechange = function () {
   if (req.readyState == 4 && req.status == 200) {
    //console.log(req.responseText);
    获取数据库中的数据,并将其转化为json对象
    var res = JSON.parse(req.responseText);
    html = ``;
    //循环遍历对象,用字量建表
    res.forEach(({ id, user, pwd, phone, email }) => {
     html += `
   <tr>
    <td>${id}</td>
    <td>${user}</td>
    <td>${pwd}</td>
    <td>${phone}</td>
    <td>${email}</td>
    <td onclick="del(${id},this)">删除</td>
    <td onclick="upd(${id})">修改</td>
   </tr>
   `
    });
    tbodys.innerHTML = html;
   }
  }
 }


 //删除数据
 function del(id, ele) {
  var req = new XMLHttpRequest();
  req.open('get', `./delect.php?id=${id}`, true);
  req.send();
  req.onreadystatechange = function () {
   if (req.readyState == 4 && req.status == 200) {
    //console.log(req.response);
    var res = JSON.parse(req.responseText);
    if (res.status) {
     //法一: 在不影响整个页面的情况下 实现页面的局部刷新  (重新请求数据更新)
     loadList();
     //法二: 点击删除   后台删除成功之后  重新加载页面 (重新渲染整个页面 网速不行时 又要转半天)      
     //location.reload();
     //法三: 点击删除   后台删除成功之后  删除dom元素 (分页时 当前页删一条少一条)
     // var tr = ele.parentElement.parentElement;
     // tr.remove();
    } else {
     alert(res.msg); //删除失败,返回失败信息
    }
   }
  }
 }


 //修改数据
 function upd(id) {
  shadow.style.display = "block";
  submit.onclick = function () {
      //获取修改后的数据
   var user = userInput.value;
   var pwd = pwdInput.value;
   var phone = phoneInput.value;
   var email = emailInput.value;
   var req = new XMLHttpRequest();
   req.open("get", `./update.php?id=${id}&user=${user}&pwd=${pwd}&phone=${phone}&email=${email}`, true);
   req.send();
   req.onreadystatechange = function () {
    if (req.readyState == 4 && req.status == 200) {
     console.log(req.responseText);
     var res = JSON.parse(req.responseText);
     if (res.status) {
         //修改成功,修改页面消失,局部刷新页面信息
      shadow.style.display = "none";
      alert(res.msg);
      loadList();
     } else {
         //修改失败,修改页面消失
      shadow.style.display = "none";
      alert(res.msg);
     }
    }
   }
  }
 }


 //模糊查询
 function cha() {
  searchBtn.onclick = function () {
      //获取查询信息
   var count = searchCon.value;
   var req = new XMLHttpRequest();
   req.open("get", `./cha.php?count=${count}`, true);
   req.send();
   req.onreadystatechange = function () {
    if (req.readyState == 4 && req.status == 200) {
     //console.log(req.response);
     //获取查询到的信息
     var res = JSON.parse(req.responseText);
     //console.log(JSON.parse(req.responseText))
     html = '';
     //如果res对象的长度中有值,则存在查找信息,否则则不存,输出没有找到数据
     if (Boolean(res.length)) {
      res.forEach(({ id, user, pwd, phone, email }) => {
       html += `
   <tr>
    <td>${id}</td>
    <td>${user}</td>
    <td>${pwd}</td>
    <td>${phone}</td>
    <td>${email}</td>
    <td onclick="del(${id},this)">删除</td>
    <td onclick="upd(${id})">修改</td>
   </tr>
   `
      });
      tbodys.innerHTML = html;
     } else {
      html = `<p >没有找到相关数据</p>`;
      tbodys.innerHTML = html;
     }
    }
   }
  }
 }

//用户退出登录,cookie中不再记录浏览器信息
 function exit() {
  setCookie("log_user", "", -7);
  setCookie("log_pwd", "", -7);
  location.reload();
 }
</script>

</html>

第八步
建表php

<?php
@header("Content-Type:text/html;charset=utf-8");
//连接其他PHP文件
require_once "conn.php";
//如果数据库连接上
if (mysqli_select_db($conn, "1911")) {
    //查询表中所有的数据
    $result = mysqli_query($conn, "select * from `userinfo`");
    $arr = array();
    //循环遍历将表中的数据全部存入 $arr 数组
    while ($item = mysqli_fetch_array($result)) {
    $list = array(); 
    //循环遍历将对应数据全部存入$list对象
    $list["id"] = $item["id"];
    $list["user"] = $item["user"];
    $list["pwd"] = $item["pwd"];
    $list["phone"] = $item["phone"];
    $list["email"] = $item["email"];
    $arr[] = $list; 
    }
    //将数组转换为json对象输出
  echo json_encode($arr);
} else {
    echo "数据库连接失败";
}

第九步
删除php

<?php
  @header("Content-Type:text/html;charset=utf-8");
  
  require_once("conn.php");
  //获取删除数据对应的id
  $id=$_GET["id"];
  
  if(mysqli_select_db($conn, "1911")){
      //删除语句
   $del= "delete from `userinfo` where id = $id";
   mysqli_query($conn,$del);
   //获取受影响的行数
   $row=mysqli_affected_rows($conn);
   $msg=array();
   if($row>0){
    $msg["status"] = true;
    $msg["msg"] = "删除成功";
   }else if($row==0){
    $msg["status"] = false;
    $msg["msg"] = "删除失败,该数据不存在";
   }else{
    $msg["status"] = false;
    $msg["msg"] = "sql 语句错误";
   }
   echo json_encode($msg);
  }else{
   echo "数据库连接失败!!";
  }
?>

第十步
修改php

<?php
@header("Content-Type:text/html;charset=utf-8");
//连接其他公共php,注意顺序
require_once "conn.php";
require_once "common.php";

//获取修改的id及用户的修改信息
$id=$_GET["id"];
$user=$_GET["user"];
$pwd=$_GET["pwd"];
$phone=$_GET["phone"];
$email=$_GET["email"];

if (mysqli_select_db($conn, "1911")) {
 $msg=array();
 //先判断用户修改的用户名,电话,邮箱是否有重复
 if(isExistUser($user)){
  $msg["status"] = false; //存在
  $msg["msg"] = "用户名已存在";
} else if (isExistPhone($phone)) {
  $msg["status"] = false; //存在
  $msg["msg"] = "手机号已存在";
} else if (isExistEmail($email)) {
  $msg["status"] = false; //存在
  $msg["msg"] = "邮箱已存在";
}else{
    //如果用户名,电话,邮箱都不相同,则修改对应信息
 $upd="UPDATE `userinfo` SET user='$user',pwd='$pwd',phone=$phone,email='$email' WHERE id=$id";
 mysqli_query($conn,$upd);
 //获取受影响的行数
 $row=mysqli_affected_rows($conn);
 if($row>0){
  $msg["status"] = true;
  $msg["msg"] = "success!";
 }else if($row==0){
  $msg["status"] = false;
  $msg["msg"] = "fail!";
 }else{
  $msg["status"] = false;
  $msg["msg"] = "sql error!";
 }
}
echo json_encode($msg);    //返回对应的json数据
 mysqli_close($conn); 
}else{
 echo "数据库连接失败";
}
?>

第十步
模糊查询php

<?php
@header("Content-Type:text/html;charset=utf-8");
require_once "conn.php";
//获取需要模糊查询的数据
$count=$_GET["count"];

if (mysqli_select_db($conn, "1911")){
    //查询用户名,电话,邮箱中是否有重合部分
 $search="SELECT * FROM `userinfo` WHERE user LIKE '%$count%' or phone LIKE '%$count%' or email LIKE  '%$count%'";
 $result=mysqli_query($conn,$search);
 $arr=array();
 //遍历符合条件的数组,存入
 while($item=mysqli_fetch_array($result)){
  $list=array();
  $list["id"] = $item["id"];
  $list["user"] = $item["user"];
  $list["pwd"] = $item["pwd"];
  $list["phone"] = $item["phone"];
  $list["email"] = $item["email"];
  $arr[] = $list; 
  }
  echo json_encode($arr);
}else{
 echo "数据库连接失败!!";
}
?>

第十一步
cookie封装js

//设置cookie
function setCookie(key, value, day, path = "/") {
 // cookie 是以键值(key,value)对形式存在的字符串   expires    path
 if (day) {
     var date = new Date();
     date.setDate(date.getDate() + day);  //过期时间
     // 字面量写法 document.cookie = `${key}=${value};expires=${date.toUTCString()};path=${path}`;
     document.cookie = key + "=" + encodeURIComponent(value) + ";expires=" + date.toUTCString() + ";path=" + path;
 } else {  
      //如果不传day  那么浏览器关闭时过期
     document.cookie = key + "=" + encodeURIComponent(value) + ";path=" + path;
 }
}


// cookie的取值   根据key(属性名)  取值(属性值)
function getCookie(key) { // 查询的键(属性名)  
 var cookie = document.cookie;
 //如果存在cookie
 if (cookie) { 
     var dataList = cookie.split("; ");    // "log_user=www; log_pwd=123123"
     // console.log(dataList);
     // 主页面只要求找用户名,循环遍历数组
     for (var i = 0; i < dataList.length; i++) {
         var item = dataList[i]; //"log_user=www", "log_pwd=123123"

         var name = item.split("=")[0];  // "log_user"   当前数据的键
         var val = item.split("=")[1];  // "www"    当前数据的值
         // console.log(item.split("="));
         if (name == key) {
             return decodeURIComponent(val);
         }
     }
 }
 return ""; // 如果查不到  返回""
}

上一篇: leetcode:78. 子集

下一篇: 进制转换