PHP combined with bootstrap and JS to realize the function of deleting, editing and searching student list

Time:2019-10-17

This small project of our own will come to an end. There may be many more bugs. Excuse me

Delete student function

PHP:

//Here is the URL from the front-end code HTML, which is obtained by $_get (see the home page for relevant HTML code and the previous blogs)
If (empty ($_get ['num ']) exit (' < H1 > can't find the student ID of the student you want to delete < / H1 > ');
$num = $_GET['num'];
$connection = mysqli_connect ('localhost ',' root ',' password ',' students_info_system ');
If (! $connection) exit ('< H1 > failed to connect to database < / H1 >');
$query = mysqli_query($connection, "delete from students where num = {$num}");
If (! $query) exit ('< H1 > the student information query failed < / H1 >');
//Note: the connection object is passed in here
$affected_rows = mysqli_affected_rows($connection);
If ($affected rows! = = 1) exit ('< H1 > deletion failed < / H1 >');
header('Location: student_info.php');

Editing student functions (the overall and adding student functions are not worse, slightly different)

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  < title > edit student < / Title >
  <link rel="stylesheet" type="text/css" href="css/Bootstrap.css" rel="external nofollow" >
</head>
<body>
  <div>
    <h1>Edit students</h1>
    <?php if (isset($error_msg)): ?>
    <div><?php echo $error_msg; ?></div>
    <?php endif ?>
    <div>
      <img src="<?php echo $current_student['photo']; ?>" alt="<?php echo $current_student['name']; ?>" width="100" height="488">
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>?id=<?php echo $current_num; ?>" method="post" enctype="multipart/form-data" autocomplete="off">
        <div>
          < input type = "number" name = "num" placeholder = "student number" value = "< PHP echo isset ($_post ['num '])? $_post ['num']: $current_student ['num '];? >" >
        </div>
        <div>
          <select name="system">
            < option > please select college / Department < / option >
            < option <? PHP echo $current_student ['system '] = = =' School of electrical engineering '?'selected': '';? > > School of electrical engineering < / option >
            < option <? PHP echo $current Gu student ['system '] = =' School of information engineering and art '?'selected': '';? > > School of information engineering and art < / option >
            < option <? PHP echo $current_student ['system '] ========'institute of international education'?'selected ':' ';? > > Institute of international education < / option >
            < option <? PHP echo $current_student ['system '] = = =' School of water conservancy and Hydropower Engineering '?'selected': ';? > > School of water conservancy and Hydropower Engineering < / option >
            < option <? PHP echo $current Gu student ['system '] = =' School of Surveying and municipal engineering '?'selected': '';? > > School of Surveying and municipal engineering < / option >
            < option <? PHP echo $current_student ['system '] = = =' School of Marxism '?'selected': '';? > > School of Marxism < / option >
            < option <? PHP echo $current_student ['system '] = = =' School of construction engineering '?'selected': '';? > > School of construction engineering < / option >
            < option <? PHP echo $current Gu student ['system '] = =' School of economics and management '?'selected': '';? > > School of economics and management < / option >
          </select>
        </div>
        <div>
          < input type = "text" name = "class" placeholder = "class" value = "< PHP echo isset ($post ['class'])? $post ['class']: $current_student ['class'];? >" >
        </div>
        <div>
          < input type = "text" name = "name" placeholder = "name" value = "< PHP echo isset ($post ['name '])? $post ['name']: $current_student ['name '];? >" >
        </div>
        <div>
          <select name="gender">
            < option value = "- 1" > please select gender < / option >
            < option <? PHP echo $current_student ['gender '] = = =' 1 '?'selected': '';? > value = "1" > male < / option >
            < option <? PHP echo $current_student ['gender '] = = =' 0 '?'selected': '';? > value = "0" > female < / option >
          </select>
        </div>
        <div>
          < label for = "birthday" > date of birth < / label >
          <input type="date" name="birthday" value="<?php echo isset($_POST['birthday']) ? $_POST['birthday'] : $current_student['birthday']; ?>">
        </div>
        <div>
          < label for = "photo" > Photo < / label >
          <input type="file" name="photo">
        </div>
        < button type = "submit" > confirm modification < / button >
      </form>
    </div>
  </div>
</body>
</html>

PHP:

If (empty ($_get ['id ']) exit (' < H1 > must specify the corresponding student number < / H1 > ');
$current_num = $_GET['id'];
$connection = mysqli_connect ('localhost ',' root ',' password ',' students_info_system ');
If (! $connection) exit ('< H1 > failed to connect to database < / H1 >');
$query = mysqli_query($connection, "select * from students where num = {$current_num} limit 1");
If (! $query) exit ('< H1 > can't find the student information you want to edit < / H1 >');
$current_student = mysqli_fetch_assoc($query);
// var_dump($current_student);
function edit_student() {
  //Var_dump ('In ');
  global $connection;
  Global $current Fu num; // current student ID
  global $current_student;
  $extra_students_query = mysqli_query($connection, "select * from students where num != {$current_num}");
  if (!$extra_students_query) {
    Exit ('< H1 > other student data query failed < / H1 >');
    // return;
  }
  //Query other students except the student
  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 '] =' please enter student number ';
    return;
  }
  //Determine whether the student number has been added (that is, the student already exists in the list)=========
  if (in_array($_POST['num'], $students_num)) {
    $globals ['error_msg '] =' the student already exists';
    return;
  }
  If (empty ($| post ['system ']) | $| post ['system'] = = = 'please select college / department'){
    $globals ['error_msg '] =' please select college / department ';
    return;
  }
  if (empty($_POST['class'])) {
    $globals ['error_msg '] =' please enter class';
    return;
  }
  if (empty($_POST['name'])) {
    $globals ['error_msg '] =' please enter name ';
    return;
  }
  if (!(isset($_POST['gender']) && $_POST['gender'] !== '-1')) {
    $globals ['error_msg '] =' please select gender ';
    return;
  }
  if (empty($_POST['birthday'])) {
    $globals ['error_msg '] =' please enter the date of birth ';
    return;
  }
  //The following processing file fields=======================================================
  //Only when there is a file uploaded can it be verified. If there is no upload, the photo will remain the same.
  // $_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 '] =' upload photo failed ';
      return;
    }
    //Verify the type of uploaded file (only pictures are allowed)
    if (strpos($_FILES['photo']['type'], 'image/') !== 0) {
      $globals ['error_msg '] =' this is not a supported file format type, please upload again ';
      return;
    }
    //The file is uploaded to a temporary address opened by the server and needs to be transferred to the local
    $image_target = 'images/' . $_FILES['photo']['name'];
    if (!move_uploaded_file($_FILES['photo']['tmp_name'], $image_target)) {
      $globals ['error_msg '] =' image upload failed ';
      return;
    }
    //Receive updated student photos
    $current_student['photo'] = (string)$image_target;
  } else {
    // var_dump($_FILES['photo']);
    //If the photo is not uploaded, the file field will not be verified, the data will be updated directly and the original photo will not be changed.
    $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);
  //Save data changes to database
  $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 '] =' update data query failed ';
    return;
  }
  $affected_rows = mysqli_affected_rows($connection);
  if ($affected_rows !== 1) {
    $globals ['error_msg '] =' modification failed ';
    return;
  }
  //Delay 2 seconds
  time_sleep_until(time() + 2);
  header('Location: student_info.php');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  edit_student();
}

Search function (using JS)

//Keyword search function - immediate function
(function (element, search_key) {
  Let table = document.getelementbyid ('table content '); // get table
  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; // get the number of hidden students (that is, the number of hidden rows in the table)
    //Get keywords to search
    const search_content = document.getElementById(search_key).value;
    // console.log(search_content);
    // console.log(typeof(search_content));
    let data = [];
    //Traversal list stores data in an array
    //1. Get the number of table rows
    for (let i = 0; i < table.children.length; i++) {
      //2. Get the number of table columns
      for (let j = 0; j < table.children[i].children.length; j++) {
        if (!data[i]) {
          //Create an array in which the contents of each row are stored to store one row of data
          data[i] = new Array();
        }
        data[i][j] = table.children[i].children[j].innerHTML.toString();
        //3. Storage data
        if (data[i][j] === '♂') {
          Data [i] [J] = 'male';
        }
        if (data[i][j] === '♀') {
          Data [i] [J] = 'female';
        }
      }
      // 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 = "total" + (table. Children. Length - hiddenstudentsnumber) + "students";
    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 = "total" + table.children.length + "students";
  document.getElementById('students_number').innerHTML = str;
})('search', 'search-key');

At the same time, add in the original student information page HTML:

<div>
      < a style = "margin right: 28px; margin left: 15px;" href = "add_student. PHP" rel = "external nofollow" > add students</a>
        // added
      <button></button>
        

      < input type = "text" autocomplete = "on" placeholder = "please enter the keyword" value = "" >
       < button type = "submit" > Click Search < / button >
    </div>

summary

The above-mentioned is the PHP combined with bootstrap combined with JS introduced by Xiaobian. We hope it can help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time!

Recommended Today

What are the new methods of visual + map technology?

Last week, Ren Xiaofeng, chief scientist of Alibaba Gaode map, made a technical exchange with you on the development of computer vision related technology and the application in the field of map travel at the online live broadcast activity of “cloud dialogue” between senior students of Alibaba. The interaction between live broadcast is hot. Especially […]