PHP 结合 Boostrap 结合 js 实现学生列表删除编辑及搜索功能


Posted in PHP onMay 21, 2019

这个自己的小项目要先告一段落了。可能还有许多bug。请见谅 

删除学生功能

PHP:

// 这里是通过前端代码HTML中的 url 传过来的,用 $_GET 来获取(相关HTML代码可以看一下到主页看一下前几条博客)
if (empty($_GET['num'])) exit('<h1>找不到您要删除的学生的学号</h1>');
$num = $_GET['num'];
$connection = mysqli_connect('localhost', 'root', '密码', 'students_info_system');
if (!$connection) exit('<h1>连接数据库失败</h1>');
$query = mysqli_query($connection, "delete from students where num = {$num}");
if (!$query) exit('<h1>该学生信息查询失败</h1>');
// 注意:这里传入的是连接对象
$affected_rows = mysqli_affected_rows($connection);
if ($affected_rows !== 1) exit('<h1>删除失败</h1>');
header('Location: student_info.php');

编辑学生功能(整体上和添加学生功能差不到,稍微有些许变化)

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>编辑学生</title>
  <link rel="stylesheet" type="text/css" href="css/Bootstrap.css" rel="external nofollow" >
</head>
<body>
  <div class="container mt-3">
    <h1 class="display-5 text-center">编辑学生</h1>
    <?php if (isset($error_msg)): ?>
    <div class="alert alert-danger"><?php echo $error_msg; ?></div>
    <?php endif ?>
    <div class="row mt-3">
      <img src="<?php echo $current_student['photo']; ?>" alt="<?php echo $current_student['name']; ?>" width="100" height="488" class="col-sm-6">
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>?id=<?php echo $current_num; ?>" method="post" enctype="multipart/form-data" autocomplete="off" class="col-sm-6">
        <div class="form-group">
          <input type="number" name="num" class="form-control" placeholder="学号" value="<?php echo isset($_POST['num']) ? $_POST['num'] : $current_student['num']; ?>">
        </div>
        <div class="form-group">
          <select class="form-control" name="system">
            <option>请选择学院/系</option>
            <option <?php echo $current_student['system'] === '电气工程学院' ? 'selected' : ''; ?>>电气工程学院</option>
            <option <?php echo $current_student['system'] === '信息工程与艺术学院' ? 'selected' : ''; ?>>信息工程与艺术学院</option>
            <option <?php echo $current_student['system'] === '国际教育学院' ? 'selected' : ''; ?>>国际教育学院</option>
            <option <?php echo $current_student['system'] === '水利水电工程学院' ? 'selected' : ''; ?>>水利水电工程学院</option>
            <option <?php echo $current_student['system'] === '测绘与市政工程学院' ? 'selected' : ''; ?>>测绘与市政工程学院</option>
            <option <?php echo $current_student['system'] === '马克思主义学院' ? 'selected' : ''; ?>>马克思主义学院</option>
            <option <?php echo $current_student['system'] === '建筑工程学院' ? 'selected' : ''; ?>>建筑工程学院</option>
            <option <?php echo $current_student['system'] === '经济与管理学院' ? 'selected' : ''; ?>>经济与管理学院</option>
          </select>
        </div>
        <div class="form-group">
          <input type="text" name="class" class="form-control" placeholder="班级" value="<?php echo isset($_POST['class']) ? $_POST['class'] : $current_student['class']; ?>">
        </div>
        <div class="form-group">
          <input type="text" name="name" class="form-control" placeholder="姓名" value="<?php echo isset($_POST['name']) ? $_POST['name'] : $current_student['name']; ?>">
        </div>
        <div class="form-group">
          <select class="form-control" name="gender">
            <option value="-1">请选择性别</option>
            <option <?php echo $current_student['gender'] === '1' ? 'selected' : ''; ?> value="1">男</option>
            <option <?php echo $current_student['gender'] === '0' ? 'selected' : ''; ?> value="0">女</option>
          </select>
        </div>
        <div class="form-group">
          <label for="birthday">出生日期</label>
          <input type="date" name="birthday" class="form-control" id="birthday" value="<?php echo isset($_POST['birthday']) ? $_POST['birthday'] : $current_student['birthday']; ?>">
        </div>
        <div class="form-group">
          <label for="photo">照片</label>
          <input type="file" name="photo" class="form-control">
        </div>
        <button type="submit" class="btn btn-info btn-block">确认修改</button>
      </form>
    </div>
  </div>
</body>
</html>

PHP:

if (empty($_GET['id'])) exit('<h1>必须指定相应的学号</h1>');
$current_num = $_GET['id'];
$connection = mysqli_connect('localhost', 'root', '密码', 'students_info_system');
if (!$connection) exit('<h1>连接数据库失败</h1>');
$query = mysqli_query($connection, "select * from students where num = {$current_num} limit 1");
if (!$query) exit('<h1>找不到您要编辑的学生信息</h1>');
$current_student = mysqli_fetch_assoc($query);
// var_dump($current_student);
function edit_student() {
  // var_dump('进来了');
  global $connection;
  global $current_num;  // 当前学生学号
  global $current_student;
  $extra_students_query = mysqli_query($connection, "select * from students where num != {$current_num}");
  if (!$extra_students_query) {
    exit('<h1>其余学生数据查询失败</h1>');
    // return;
  }
  // 查询除该学生以外的其他学生
  while ($student = mysqli_fetch_assoc($extra_students_query)) {
    // var_dump($student);
    $students_num[] = $student['num'];
  }
  // var_dump($students_num);
  // var_dump($_FILES['photo']);
  // var_dump($_POST['gender']);
  if (empty($_POST['num'])) {
    $GLOBALS['error_msg'] = '请输入学号';
    return;
  }
  // 判断该学号是否已经被添加(即列表中已存在该学生)=========
  if (in_array($_POST['num'], $students_num)) {
    $GLOBALS['error_msg'] = '该学生已存在';
    return;
  }
  if (empty($_POST['system']) || $_POST['system'] === '请选择学院/系') {
    $GLOBALS['error_msg'] = '请选择学院/系';
    return;
  }
  if (empty($_POST['class'])) {
    $GLOBALS['error_msg'] = '请输入班级';
    return;
  }
  if (empty($_POST['name'])) {
    $GLOBALS['error_msg'] = '请输入姓名';
    return;
  }
  if (!(isset($_POST['gender']) && $_POST['gender'] !== '-1')) {
    $GLOBALS['error_msg'] = '请选择性别';
    return;
  }
  if (empty($_POST['birthday'])) {
    $GLOBALS['error_msg'] = '请输入出生日期';
    return;
  }
  // 以下处理文件域=======================================================
  // 当有文件上传时才验证,没有上传则照片不变
  // $_FILES['photo'] = $current_student['photo'];
  // var_dump($_FILES['photo']);
  if ($_FILES['photo']['name'] !== '') {
    // var_dump($_FILES['photo']);
    // var_dump($_FILES['photo']);
    if ($_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
      $GLOBALS['error_msg'] = '上传照片失败';
      return;
    }
    // 验证上传文件的类型(只允许图片)
    if (strpos($_FILES['photo']['type'], 'image/') !== 0) {
      $GLOBALS['error_msg'] = '这不是支持的文件格式类型,请重新上传';
      return;
    }
    // 文件上传到了服务端开辟的一个临时地址,需要转移到本地
    $image_target = 'images/' . $_FILES['photo']['name'];
    if (!move_uploaded_file($_FILES['photo']['tmp_name'], $image_target)) {
      $GLOBALS['error_msg'] = '图片上传失败';
      return;
    }
    // 接收更新过的学生照片
    $current_student['photo'] = (string)$image_target;
  } else {
    // var_dump($_FILES['photo']);
    // 如果照片没有上传则不进行验证文件域,直接更新数据且不改变原来的照片
    $current_student['num'] = $_POST['num'];
    $current_student['system'] = $_POST['system'];
    $current_student['class'] = $_POST['class'];
    $current_student['name'] = $_POST['name'];
    $current_student['gender'] = $_POST['gender'];
    $current_student['birthday'] = $_POST['birthday'];
  }
  // var_dump($current_num);
  // 将数据修改存放到数据库
  $update_query = mysqli_query($connection, "update students set `num` = '{$current_student['num']}', `system` = '{$current_student['system']}', `class` = '{$current_student['class']}', `name` = '{$current_student['name']}', `gender` = '{$current_student['gender']}', `birthday` = '{$current_student['birthday']}', `photo` = '{$current_student['photo']}' where `num` = {$current_num}");
  if (!$update_query) {
    $GLOBALS['error_msg'] = '更新数据查询失败';
    return;
  }
  $affected_rows = mysqli_affected_rows($connection);
  if ($affected_rows !== 1) {
    $GLOBALS['error_msg'] = '修改失败';
    return;
  }
  // 延迟2秒
  time_sleep_until(time() + 2);
  header('Location: student_info.php');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  edit_student();
}

搜索功能(用js)

// 关键词搜索功能----立即函数
(function (element, search_key) {
  let table = document.getElementById('table-content'); // 获取表格
  function in_array_item (item, array) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].indexOf(item) != -1) {
        return true;
      }
    }
    return false;
  }
  function response () {
    let hiddenStudentsNumber = 0;             // 获取隐藏的学生个数(即表格隐藏行数)
    // 获取要搜索的关键词
    const search_content = document.getElementById(search_key).value;
    // console.log(search_content);
    // console.log(typeof(search_content));
    let data = [];
    // 遍历列表将数据存储到一个数组中
    // 1.获取表格行数
    for (let i = 0; i < table.children.length; i++) {
      // 2.获取表格列数
      for (let j = 0; j < table.children[i].children.length; j++) {
        if (!data[i]) {
          // 在数组中创键每一行内容存放的数组,用于存放一行数据
          data[i] = new Array();
        }
        data[i][j] = table.children[i].children[j].innerHTML.toString();
        // 3.存放数据
        if (data[i][j] === '♂') {
          data[i][j] = '男';
        }
        if (data[i][j] === '♀') {
          data[i][j] = '女';
        }
      }
      // console.log(data[i]);
      if (search_content == '') {
        table.children[i].style.display = '';
      } else {
        if (in_array_item(search_content, data[i])) {
          table.children[i].style.display = '';
        } else {
          table.children[i].style.display = 'none';
          hiddenStudentsNumber += 1;
        }
      }
    }
    console.log(hiddenStudentsNumber);
    let str = "共有" + (table.children.length - hiddenStudentsNumber) + "名学生";
    document.getElementById('students_number').innerHTML = str;
  }
  const searchButton = document.getElementById(element);
  searchButton.addEventListener('click', function () {
    response();
  });
  document.addEventListener('keydown', function (event) {
    if (event.keyCode === 13) {
      response();
    }
  });
  let str = "共有" + table.children.length + "名学生";
  document.getElementById('students_number').innerHTML = str;
})('search', 'search-key');

同时在原有的学生信息页面HTML添加:

<div class="row mt-3">
      <a class="btn btn-info col-sm-2" style="margin-right: 28px; margin-left: 15px;" href="add_student.php" rel="external nofollow" >添加学生</a>
// 添加的
      <button class="btn btn-info align-middle" id="students_number"></button>


      <input type="text" class="form-control col-sm-6 ml-2" autocomplete="on" placeholder="请输入关键词" value="" id="search-key">
       <button type="submit" class="btn btn-info col-sm-2 ml-2" id="search">点击搜索</button>
    </div>

总结

以上所述是小编给大家介绍的PHP 结合 Boostrap 结合 js 实现学生列表删除编辑及搜索功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

PHP 相关文章推荐
用PHP写的MySQL数据库用户认证系统代码
Mar 22 PHP
Codeigniter框架的更新事务(transaction)BUG及解决方法
Jul 25 PHP
PHP多文件上传实例
Jul 09 PHP
PHP目录与文件操作技巧总结(创建,删除,遍历,读写,修改等)
Sep 11 PHP
golang 调用 php7详解及实例
Jan 04 PHP
超强多功能php绿色集成环境详解
Jan 25 PHP
2017年最好用的9个php开发工具推荐(超好用)
Oct 23 PHP
thinkPHP通用控制器实现方法示例
Nov 23 PHP
php 截取中英文混合字符串的方法
May 31 PHP
PHP删除字符串中非字母数字字符方法总结
Jan 20 PHP
详解PHP 7.4 中数组延展操作符语法知识点
Jul 19 PHP
Laravel基础-关于引入公共文件的两种方式
Oct 18 PHP
thinkphp5框架API token身份验证功能示例
May 21 #PHP
php curl操作API接口类完整示例
May 21 #PHP
PHP钩子实现方法解析
May 21 #PHP
php面向对象程序设计中self与static的区别分析
May 21 #PHP
PHP经典设计模式之依赖注入定义与用法详解
May 21 #PHP
PHP常见过waf webshell以及最简单的检测方法
May 21 #PHP
PHP __call()方法实现委托示例
May 20 #PHP
You might like
eAccelerator的安装与使用详解
2013/06/13 PHP
PHP获取本周第一天和最后一天示例代码
2014/02/24 PHP
如何让thinkphp在模型中自动完成session赋值小教程
2014/09/05 PHP
在Laravel中使用DataTables插件的方法
2018/05/29 PHP
javascript 简单高效判断数据类型 系列函数 By shawl.qiu
2007/03/06 Javascript
ExtJs 3.1 XmlTreeLoader Example Error
2010/02/09 Javascript
JQuery入门——移除绑定事件unbind方法概述及应用
2013/02/05 Javascript
jQuery实现可拖动的浮动层完整代码
2013/05/27 Javascript
EXTjs4.0的store的findRecord的BUG演示代码
2013/06/08 Javascript
基于jquery animate操作css样式属性小结
2015/11/27 Javascript
JS不用正则验证输入的字符串是否为空(包含空格)的实现代码
2016/06/14 Javascript
下一代Bootstrap的5个特点 超酷炫!
2016/06/17 Javascript
AngularJS 输入验证详解及实例代码
2016/07/28 Javascript
JS简单判断字符在另一个字符串中出现次数的2种常用方法
2017/04/20 Javascript
使用 Node.js 对文本内容分词和关键词抽取
2017/05/27 Javascript
js canvas实现放大镜查看图片功能
2017/06/08 Javascript
JS 中使用Promise 实现红绿灯实例代码(demo)
2017/10/20 Javascript
详解webpack3编译兼容IE8的正确姿势
2017/12/21 Javascript
Puppeteer 爬取动态生成的网页实战
2018/11/14 Javascript
vue 取出v-for循环中的index值实例
2019/11/09 Javascript
用jQuery实现抽奖程序
2020/04/12 jQuery
[01:08:17]2018DOTA2亚洲邀请赛3月29日 小组赛B组 EG VS VGJ.T
2018/03/30 DOTA
python使用PyGame模块播放声音的方法
2015/05/20 Python
利用Python命令行传递实例化对象的方法
2016/11/02 Python
python访问抓取网页常用命令总结
2017/04/11 Python
浅谈pandas中shift和diff函数关系
2018/04/08 Python
Python实现Linux监控的方法
2019/05/16 Python
Python 内置变量和函数的查看及说明介绍
2019/12/25 Python
用Python爬取LOL所有的英雄信息以及英雄皮肤的示例代码
2020/07/13 Python
css3实现背景颜色渐变让图片不再是唯一的实现方式
2012/12/18 HTML / CSS
什么是JNDI的上下文?如何初始化JNDI上下文
2012/03/10 面试题
Unix/Linux开发面试题
2016/08/16 面试题
给酒店员工的表扬信
2014/01/11 职场文书
内蒙古鄂尔多斯市市长寄语
2014/04/10 职场文书
体育课课后反思
2014/04/24 职场文书
PostgreSQL事务回卷实战案例详析
2022/03/25 PostgreSQL