Chương trình quản lý sinh viên PHP

Để củng cố và thực hành những kiến thức chúng ta đã học qua, mời bạn đọc cùng eLib.VN tham khảo project về quản lý sinh viên cơ bản sau.

Chương trình quản lý sinh viên PHP

1. Chương trình quản lý sinh viên lưu Session

Đầu tiên bạn khởi tạo một số file sau:

  • students.php: Đây là file lưu trữ các hàm lấy danh sách, thêm, xóa và sửa sinh viên
  • student-list.php: Đây là file hiển thị danh sách sinh viên
  • student-add.php: Đây là file thực hiện hai thao tác đó là thêm và sửa
  • student-delete.php: Đây là file thực hiện thao tác xóa sinh viên.

Viết thư viện quản lý sinh viên bằng Session

Đầu tiên bạn mở file students.php lên và nhập vào nội dung sau:

 
session_start();

// Lấy danh sach sinh viên trong session
function getAllStudents()
{
    return isset($_SESSION['students']) ? $_SESSION['students'] : array();
}

// Lấy chi tiết một sinh viên dựa vào sinh viên id
function getStudent($student_id)
{
    // Lấy danh sách sinh viên để tìm
    $students = getAllStudents();
     
    // Duyệt qua từng phần tử, nếu xuất hiện ID giống nhau thì tức là đã tìm thấy sinh viên
    foreach ($students as $item)
    {
        if ($item['student_id'] == $student_id){
            return $item;
        }
    }
     
    return array();
}

// Xóa sinh viên bởi sinh viên ID
function deleteStudent($student_id)
{
    // Lấy danh sách sinh viên để tìm
    $students = getAllStudents();
     
    /// Duyệt qua từng phần tử, nếu xuất hiện ID giống nhau thì tức là đã tìm thấy sinh viên
    foreach ($students as $key => $item)
    {
        // Đã tìm thấy thì dùng hàm unset để xóa
        if ($item['student_id'] == $student_id){
            unset($students[$key]);
        }
    }
     
    // Cập nhật lại Session
    $_SESSION['students'] = $students;
     
    return $students;
}

// Hàm thêm và sửa sinh viên
function updateStudent($student_id, $student_name, $student_email)
{
    // Lấy danh sách sinh viên
    $students = getAllStudents();
     
    // Khai báo cấu trúc lưu trữ một sinh viên
    $new_student = array(
        'student_id' => $student_id,
        'student_name' => $student_name,
        'student_email' => $student_email
    );
     
    // Trường hợp update
    $is_update_action = false;
    foreach ($students as $key => $item)
    {
        if ($item['student_id'] == $student_id){
            $students[$key] = $new_student;
            $is_update_action = true; // khai báo đây là action update
        }
    }
     
    // Trường hợp add, tứ là $is_update_action = false
    if (!$is_update_action){
        $students[] = $new_student;
    }
     
    // Cập nhật dữ liệu trong Session
    $_SESSION['students'] = $students;
     
    return $students;
}
Kể từ bây giờ các file còn lại sẽ require file này vào để sử dụng thư viện.

Hiển thị danh sách sinh viên

Bạn mở file student-list.php lên và copy nội dung sau vào:

 
<?php
require ("/students.php");
$students = getAllStudents();
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Danh sách sinh viên</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="student-add.php">THÊM</a>
        <table border="1" cellspacing="0" cellpadding="10">
            <tr>
                <td>ID</td>
                <td>Fullname</td>
                <td>Birthday</td>
                <td>Action</td>
            </tr>
            <?php foreach ($students as $item){ ?>
            <tr>
                <td><?php echo $item['student_id']; ?></td>
                <td>
                    <a href="student-add.php?id=<?php echo $item['student_id']; ?>"><?php echo $item['student_name']; ?></a>
                </td>
                <td><?php echo $item['student_email']; ?></td>
                <td>
                    <form method="post" action="student-delete.php">
                        <input type="hidden" value="<?php echo $item['student_id']; ?>" name="student_id"/>
                        <input onclick="return confirm('Ban co chac muon xoa sinh vien nay hay khong?');" type="submit" value="Delete" name="delete"/>
                    </form>
                </td>
            </tr>
            <?php } ?>
        </table>
    </body>
</html>

Thư nhất: Trong file này mình đã dùng hàm getAllStudents() để lấy danh sách sinh viên, đồng thời sử dụng vòng lặp foreach để lặp qua từng sinh viên và in ra trình duyệt.

require ("/students.php");
$students = getAllStudents();

Thứ hai: Trong mỗi vòng lặp mình có tạo một cái form dùng để delete, trong form có một input hidden lưu trữ sinhvien_id để khi người dùng nhấn delete ta sẽ biết là cần delete sinh viên id nào.

 
<?php foreach ($students as $item){ ?>
<tr>
    <td><?php echo $item['student_id']; ?></td>
    <td>
        <a href="student-add.php?id=<?php echo $item['student_id']; ?>"><?php echo $item['student_name']; ?></a>
    </td>
    <td><?php echo $item['student_email']; ?></td>
    <td>
        <form method="post" action="student-delete.php">
            <input type="hidden" value="<?php echo $item['student_id']; ?>" name="student_id"/>
            <input onclick="return confirm('Ban co chac muon xoa sinh vien nay hay khong?');" type="submit" value="Delete" name="delete"/>
        </form>
    </td>
</tr>
<?php } ?>

Thứ ba: Trong phần tên sinh viên mình gắn thẻ a trỏ đến trang student-add.php, bạn để ý là URL mình có bổ sung thêm một cái query string đó là student-add.php?id=<?php echo $item['student_id']; ?>. Lúc này ở bên file student-add.php sẽ kiểm tra nếu URL có id thì tức là thao tác edit, ngược lại là thao tác add.

<form method="post" action="student-delete.php">
    <input type="hidden" value="<?php echo $item['student_id']; ?>" name="student_id"/>
    <input onclick="return confirm('Ban co chac muon xoa sinh vien nay hay khong?');" type="submit" value="Delete" name="delete"/>
</form>

 

Thêm và sửa sinh viên

Bạn mở file student-add.php lên và dán nội dung sau vào:

 
<?php
require ("/students.php");

// Biến lưu trữ data và error
// Biến này phải khai báo ở đây để ở dưới sử dụng sẽ không bị lỗi
$data = array();
$errors = array();

// Biến kiểm tra có phải action edit hay không
$is_update_action = false;

// Trường hợp edit thì ta lấy thông tin để show ra cho người dùng thấy
if (!empty($_GET['id']))
{
    $data = getStudent($_GET['id']);
    $is_update_action  = true;
}

// Nếu người dùng click vào nút submit
if (!empty($_POST['add_student']))
{
     
    // Lấy thông tin
    $data['student_id'] = isset($_POST['id']) ? $_POST['id'] : '';
    $data['student_name'] = isset($_POST['name']) ? $_POST['name'] : '';
    $data['student_email'] = isset($_POST['email']) ? $_POST['email'] : '';
     
    // Validate
    if (empty($data['student_id'])){
        $errors['student_id'] = 'Ban chua nhap ID';
    }
     
    if (empty($data['student_name'])){
        $errors['student_name'] = 'Ban chua nhap name';
    }
     
    if (empty($data['student_email'])){
        $errors['student_email'] = 'Ban chua nhap Email';
    }
     
    //  Nếu dữ liệu hợp lệ thì thực hiện thao tác update thông tin
    // đồng thời redirect về trang danh sách
    if (empty($errors)){
        updateStudent($data['student_id'], $data['student_name'], $data['student_email']);
        header("Location:student-list.php");
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Thêm sinh viên</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="student-list.php">BACK</a>
        <form method="post">
            <table border="1" cellspacing="0" cellpadding="10">
                <tr>
                    <td>Id</td>
                    <td>
                        <input type="text" name="id" value="<?php echo !empty($data['student_id']) ? $data['student_id'] : ''; ?>" />
                        <?php echo !empty($errors['student_id']) ? $errors['student_id'] : ''; ?>
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td>
                        <input type="text" name="name" value="<?php echo !empty($data['student_name']) ? $data['student_name'] : ''; ?>" />
                        <?php echo !empty($errors['student_name']) ? $errors['student_name'] : ''; ?>
                    </td>
                </tr>
                <tr>
                    <td>Email</td>
                    <td>
                        <input type="text" name="email" value="<?php echo !empty($data['student_email']) ? $data['student_email'] : ''; ?>" />
                        <?php echo !empty($errors['student_email']) ? $errors['student_email'] : ''; ?>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="add_student" value="<?php echo ($is_update_action) ? "Cap nhat" : "Them moi"; ?>" /></td>
                </tr>
            </table>
        </form>
    </body>
</html>

File này khó hơn một chút xíu là thực hiện cả hai thao tác edit và add luôn, bạn hãy để ý từng dòng comment của mình thật kỹ nhé.

Xóa sinh viên

Bạn mở file student-delete.php lên và dán nội dung sau vào:

// Nếu là delete thì thực hiện thao tác này
if (!empty($_POST['delete']))
{
    require ("/students.php");
    $student_id = isset($_POST['student_id']) ? $_POST['student_id'] : '';
    deleteStudent($student_id);
}

// Cuối cùng là chuyển hướng về trang danh sách
header("Location:student-list.php");

 

Phần delete này là dễ nhất phải không các bạn :)

2. Chương trình quản lý sinh viên PHP lưu database

Xây dựng CSDL quản lý sinh viên

Chúng ta chỉ lưu trữ một bảng với các thông tin như sau: sv_id, sv_name, sv_sex, sv_birthday. Bạn mở phpmyadmin lên và tạo một database tên là qlsv_db, sau đó chạy câu SQL sau để tạo mới table tv_sinhvien.

 
CREATE TABLE IF NOT EXISTS `tb_sinhvien` (
  `sv_id` int(11) NOT NULL AUTO_INCREMENT,
  `sv_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sv_sex` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sv_birthday` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`sv_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;

--
-- Dumping data for table `tb_sinhvien`
--

INSERT INTO `tb_sinhvien` (`sv_id`, `sv_name`, `sv_sex`, `sv_birthday`) VALUES
(1, 'Nguyễn Văn Cường', 'Nam', '20-11-2015'),
(2, 'Đặng Hoàng Chương', 'Nam', '10-12-2014'),
(3, 'Nguyễn Phú Cường', 'Nam', '30-01-1990'),
(4, 'Nguyễn Thị Thập', 'Nữ¯', '20-11-2011');

Trong câu SQL trên mình đã thêm 4 records để demo nhé các bạn.

Xây dựng thư viện quản lý sinh viên

Chúng ta sẽ viết một thư viện quản lý sinh viên thực hiện các thao tác như hiển thị danh sách, thêm, xóa và sửa sinh viên. Tuy nhiên trước khi vào bài thì chúng ta cần phải tạo cấu trúc folder đã nhé. Bạn hãy tạo danh sách các file như trong hình sau:

Cần chuẩn bị một số file như sau:

  • libs/students.php sẽ chứa các hàm xử lý database sinh viên
  • student-add.php sẽ xử lý thao tác thêm sinh viên
  • student-delete.php sẽ xử lý thao tác xóa sinh viên
  • student-edit.php sẽ xử lý thao tác sửa sinh viên
  • student-list.php sẽ xử lý thao tác hiển thị danh sách sinh viên.

Bạn mở file libs/students.php lên và nhập vào nội dung sau:

 
// Biến kết nối toàn cục
global $conn;

// Hàm kết nối database
function connect_db()
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Nếu chưa kết nối thì thực hiện kết nối
    if (!$conn){
        $conn = mysqli_connect('localhost', 'root', 'vertrigo', 'qlsv_db') or die ('Can't not connect to database');
        // Thiết lập font chữ kết nối
        mysqli_set_charset($conn, 'utf8');
    }
}

// Hàm ngắt kết nối
function disconnect_db()
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Nếu đã kêt nối thì thực hiện ngắt kết nối
    if ($conn){
        mysqli_close($conn);
    }
}

// Hàm lấy tất cả sinh viên
function get_all_students()
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Hàm kết nối
    connect_db();
     
    // Câu truy vấn lấy tất cả sinh viên
    $sql = "select * from tb_sinhvien";
     
    // Thực hiện câu truy vấn
    $query = mysqli_query($conn, $sql);
     
    // Mảng chứa kết quả
    $result = array();
     
    // Lặp qua từng record và đưa vào biến kết quả
    if ($query){
        while ($row = mysqli_fetch_assoc($query)){
            $result[] = $row;
        }
    }
     
    // Trả kết quả về
    return $result;
}

// Hàm lấy sinh viên theo ID
function get_student($student_id)
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Hàm kết nối
    connect_db();
     
    // Câu truy vấn lấy tất cả sinh viên
    $sql = "select * from tb_sinhvien where sv_id = {$student_id}";
     
    // Thực hiện câu truy vấn
    $query = mysqli_query($conn, $sql);
     
    // Mảng chứa kết quả
    $result = array();
     
    // Nếu có kết quả thì đưa vào biến $result
    if (mysqli_num_rows($query) > 0){
        $row = mysqli_fetch_assoc($query);
        $result = $row;
    }
     
    // Trả kết quả về
    return $result;
}

// Hàm thêm sinh viên
function add_student($student_name, $student_sex, $student_birthday)
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Hàm kết nối
    connect_db();
     
    // Chống SQL Injection
    $student_name = addslashes($student_name);
    $student_sex = addslashes($student_sex);
    $student_birthday = addslashes($student_birthday);
     
    // Câu truy vấn thêm
    $sql = "
            INSERT INTO tb_sinhvien(sv_name, sv_sex, sv_birthday) VALUES
            ('$student_name','$student_sex','$student_birthday')
    ";
     
    // Thực hiện câu truy vấn
    $query = mysqli_query($conn, $sql);
     
    return $query;
}


// Hàm sửa sinh viên
function edit_student($student_id, $student_name, $student_sex, $student_birthday)
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Hàm kết nối
    connect_db();
     
    // Chống SQL Injection
    $student_name       = addslashes($student_name);
    $student_sex        = addslashes($student_sex);
    $student_birthday   = addslashes($student_birthday);
     
    // Câu truy sửa
    $sql = "
            UPDATE tb_sinhvien SET
            sv_name = '$student_name',
            sv_sex = '$student_sex',
            sv_birthday = '$student_birthday'
            WHERE sv_id = $student_id
    ";
     
    // Thực hiện câu truy vấn
    $query = mysqli_query($conn, $sql);
     
    return $query;
}


// Hàm xóa sinh viên
function delete_student($student_id)
{
    // Gọi tới biến toàn cục $conn
    global $conn;
     
    // Hàm kết nối
    connect_db();
     
    // Câu truy sửa
    $sql = "
            DELETE FROM tb_sinhvien
            WHERE sv_id = $student_id
    ";
     
    // Thực hiện câu truy vấn
    $query = mysqli_query($conn, $sql);
     
    return $query;
}

Bạn nhớ thay đổi thông tin kết nối cho phù hợp với máy của bạn nhé. Ý nghĩa của từng hàm mình đã comment rất rõ ràng trong code rồi nên mình không giải thích gì thêm.

Hiển thị danh sách sinh viên

Bạn mở file student-list.php lên và nhập vào nội dung sau:

 
<?php
require './libs/students.php';
$students = get_all_students();
disconnect_db();
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Danh sách sinh vien</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Danh sách sinh vien</h1>
        <a href="student-add.php">Thêm sinh viên</a> <br/> <br/>
        <table width="100%" border="1" cellspacing="0" cellpadding="10">
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>Gender</td>
                <td>Birthday</td>
                <td>Options</td>
            </tr>
            <?php foreach ($students as $item){ ?>
            <tr>
                <td><?php echo $item['sv_id']; ?></td>
                <td><?php echo $item['sv_name']; ?></td>
                <td><?php echo $item['sv_sex']; ?></td>
                <td><?php echo $item['sv_birthday']; ?></td>
                <td>
                    <form method="post" action="student-delete.php">
                        <input onclick="window.location = 'student-edit.php?id=<?php echo $item['sv_id']; ?>'" type="button" value="Sửa"/>
                        <input type="hidden" name="id" value="<?php echo $item['sv_id']; ?>"/>
                        <input onclick="return confirm('Bạn có chắc muốn xóa không?');" type="submit" name="delete" value="Xóa"/>
                    </form>
                </td>
            </tr>
            <?php } ?>
        </table>
    </body>
</html>

Chức năng thêm sinh viên

Bạn mở file student-add.php lên và nhập vào nội dung sau:

 
<?php

require './libs/students.php';

// Nếu người dùng submit form
if (!empty($_POST['add_student']))
{
    // Lay data
    $data['sv_name']        = isset($_POST['name']) ? $_POST['name'] : '';
    $data['sv_sex']         = isset($_POST['sex']) ? $_POST['sex'] : '';
    $data['sv_birthday']    = isset($_POST['birthday']) ? $_POST['birthday'] : '';
     
    // Validate thong tin
    $errors = array();
    if (empty($data['sv_name'])){
        $errors['sv_name'] = 'Chưa nhập tên sinh vien';
    }
     
    if (empty($data['sv_sex'])){
        $errors['sv_sex'] = 'Chưa nhập giới tính sinh vien';
    }
     
    // Neu ko co loi thi insert
    if (!$errors){
        add_student($data['sv_name'], $data['sv_sex'], $data['sv_birthday']);
        // Trở về trang danh sách
        header("location: student-list.php");
    }
}

disconnect_db();
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Thêm sinh vien</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Thêm sinh vien </h1>
        <a href="student-list.php">Trở về</a> <br/> <br/>
        <form method="post" action="student-add.php">
            <table width="50%" border="1" cellspacing="0" cellpadding="10">
                <tr>
                    <td>Name</td>
                    <td>
                        <input type="text" name="name" value="<?php echo !empty($data['sv_name']) ? $data['sv_name'] : ''; ?>"/>
                        <?php if (!empty($errors['sv_name'])) echo $errors['sv_name']; ?>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        <select name="sex">
                            <option value="Nam">Nam</option>
                            <option value="Nữ" <?php if (!empty($data['sv_sex']) && $data['sv_sex'] == 'Nữ') echo 'selected'; ?>>Nu</option>
                        </select>
                        <?php if (!empty($errors['sv_sex'])) echo $errors['sv_sex']; ?>
                    </td>
                </tr>
                <tr>
                    <td>Birthday</td>
                    <td>
                        <input type="text" name="birthday" value="<?php echo !empty($data['sv_birthday']) ? $data['sv_birthday'] : ''; ?>"/>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="submit" name="add_student" value="Lưu"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

Chức năng sửa sinh viên

Bạn mở file student-edit.php lên và nhập vào nội dung sau:

 
<?php

require './libs/students.php';

// Lấy thông tin hiển thị lên để người dùng sửa
$id = isset($_GET['id']) ? (int)$_GET['id'] : '';
if ($id){
    $data = get_student($id);
}

// Nếu không có dữ liệu tức không tìm thấy sinh viên cần sửa
if (!$data){
   header("location: student-list.php");
}

// Nếu người dùng submit form
if (!empty($_POST['edit_student']))
{
    // Lay data
    $data['sv_name']        = isset($_POST['name']) ? $_POST['name'] : '';
    $data['sv_sex']         = isset($_POST['sex']) ? $_POST['sex'] : '';
    $data['sv_birthday']    = isset($_POST['birthday']) ? $_POST['birthday'] : '';
    $data['sv_id']          = isset($_POST['id']) ? $_POST['id'] : '';
     
    // Validate thong tin
    $errors = array();
    if (empty($data['sv_name'])){
        $errors['sv_name'] = 'Chưa nhập tên sinh vien';
    }
     
    if (empty($data['sv_sex'])){
        $errors['sv_sex'] = 'Chưa nhập giới tính sinh vien';
    }
     
    // Neu ko co loi thi insert
    if (!$errors){
        edit_student($data['sv_id'], $data['sv_name'], $data['sv_sex'], $data['sv_birthday']);
        // Trở về trang danh sách
        header("location: student-list.php");
    }
}

disconnect_db();
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Thêm sinh vien</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Thêm sinh vien </h1>
        <a href="student-list.php">Trở về</a> <br/> <br/>
        <form method="post" action="student-edit.php?id=<?php echo $data['sv_id']; ?>">
            <table width="50%" border="1" cellspacing="0" cellpadding="10">
                <tr>
                    <td>Name</td>
                    <td>
                        <input type="text" name="name" value="<?php echo $data['sv_name']; ?>"/>
                        <?php if (!empty($errors['sv_name'])) echo $errors['sv_name']; ?>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        <select name="sex">
                            <option value="Nam">Nam</option>
                            <option value="Nữ" <?php if ($data['sv_sex'] == 'Nữ') echo 'selected'; ?>>Nu</option>
                        </select>
                        <?php if (!empty($errors['sv_sex'])) echo $errors['sv_sex']; ?>
                    </td>
                </tr>
                <tr>
                    <td>Birthday</td>
                    <td>
                        <input type="text" name="birthday" value="<?php echo $data['sv_birthday']; ?>"/>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="hidden" name="id" value="<?php echo $data['sv_id']; ?>"/>
                        <input type="submit" name="edit_student" value="Lưu"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

Điểm chú ý ở file này là ta sẽ dựa vào ID trên URL để lấy thông tin sinh viên cần sửa và hiển thị ra các ô input.

Chức năng xóa sinh viên

Chức năng này khá đơn giản, nó sẽ dựa vào thông tin id của sinh viên để xóa. Bạn mở file student-delete.php lên và nhập vào nội dung sau:

 
require './libs/students.php';

// Thực hiện xóa
$id = isset($_POST['id']) ? (int)$_POST['id'] : '';
if ($id){
    delete_student($id);
}

// Trở về trang danh sách
header("location: student-list.php");

Trên đây là hai project về quản lý sinh viên đơn giản bằng session và bằng Database. Chúng tôi hy vọng bài viết sẽ dễ hiểu và áp dụng được cho quá trình làm việc sau này. Chúc các bạn thành công!

 

 

Ngày:10/10/2020 Chia sẻ bởi:Hoang Oanh Nguyen

CÓ THỂ BẠN QUAN TÂM