ฝึกสร้างฐานข้อมูลนักเรียนด้วย PHP

สร้างตารางเก็บข้อมูลนักเรียน tbl_student

โครงสร้างตารางฐานข้อมูลใน Phpmyadmin

คลิกคำสั่ง SQL แล้วคัดลอก code ในการสร้างตารางฐานข้อมูล

CREATE TABLE `tbl_student` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `fname` varchar(100) NOT NULL,  `lname` varchar(100) NOT NULL,  `phone` varchar(10) NOT NULL,  `class` varchar(255) NOT NULL,  `datecreate` timestamp NOT NULL DEFAULT current_timestamp(),  PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci


ไฟล์ style.css

เก็บข้อมูลการแสดงผล อักษร สี ขนาด สีพื้นหลัง และระยะห่าง ฯลฯ

* {
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
body {
    background-color: #FFFFFF;
    margin: 0;
}
.navtop {
    background-color: #3f69a8;
    height: 60px;
    width: 100%;
    border: 0;
}
.navtop div {
    display: flex;
    margin: 0 auto;
    width: 1000px;
    height: 100%;
}
.navtop div h1, .navtop div a {
    display: inline-flex;
    align-items: center;
}
.navtop div h1 {
    flex: 1;
    font-size: 24px;
    padding: 0;
    margin: 0;
    color: #ecf0f6;
    font-weight: normal;
}
.navtop div a {
    padding: 0 20px;
    text-decoration: none;
    color: #c5d2e5;
    font-weight: bold;
}
.navtop div a i {
    padding: 2px 8px 0 0;
}
.navtop div a:hover {
    color: #ecf0f6;
}
.content {
    width: 1000px;
    margin: 0 auto;
}
.content h2 {
    margin: 0;
    padding: 25px 0;
    font-size: 22px;
    border-bottom: 1px solid #ebebeb;
    color: #666666;
}
.read .create-contact {
    display: inline-block;
    text-decoration: none;
    background-color: #38b673;
    font-weight: bold;
    font-size: 14px;
    color: #FFFFFF;
    padding: 10px 15px;
    margin: 15px 0;
}
.read .create-contact:hover {
    background-color: #32a367;
}
.read .pagination {
    display: flex;
    justify-content: flex-end;
}
.read .pagination a {
    display: inline-block;
    text-decoration: none;
    background-color: #a5a7a9;
    font-weight: bold;
    color: #FFFFFF;
    padding: 5px 10px;
    margin: 15px 0 15px 5px;
}
.read .pagination a:hover {
    background-color: #999b9d;
}
.read table {
    width: 100%;
    padding-top: 30px;
    border-collapse: collapse;
}
.read table thead {
    background-color: #ebeef1;
    border-bottom: 1px solid #d3dae0;
}
.read table thead td {
    padding: 10px;
    font-weight: bold;
    color: #767779;
    font-size: 14px;
}
.read table tbody tr {
    border-bottom: 1px solid #d3dae0;
}
.read table tbody tr:nth-child(even) {
    background-color: #fbfcfc;
}
.read table tbody tr:hover {
    background-color: #376ab7;
}
.read table tbody tr:hover td {
    color: #FFFFFF;
}
.read table tbody tr:hover td:nth-child(1) {
    color: #FFFFFF;
}
.read table tbody tr td {
    padding: 10px;
}
.read table tbody tr td:nth-child(1) {
    color: #a5a7a9;
}
.read table tbody tr td.actions {
    padding: 8px;
    text-align: right;
}
.read table tbody tr td.actions .edit, .read table tbody tr td.actions .trash {
    display: inline-flex;
    text-align: right;
    text-decoration: none;
    color: #FFFFFF;
    padding: 10px 12px;
}
.read table tbody tr td.actions .trash {
    background-color: #b73737;
}
.read table tbody tr td.actions .trash:hover {
    background-color: #a33131;
}
.read table tbody tr td.actions .edit {
    background-color: #37afb7;
}
.read table tbody tr td.actions .edit:hover {
    background-color: #319ca3;
}
.update form {
    padding: 15px 0;
    display: flex;
    flex-flow: wrap;
}
.update form label {
    display: inline-flex;
    width: 400px;
    padding: 10px 0;
    margin-right: 25px;
}
.update form input {
    padding: 10px;
    width: 400px;
    margin-right: 25px;
    margin-bottom: 15px;
    border: 1px solid #cccccc;
}
.update form input[type="submit"] {
    display: block;
    background-color: #38b673;
    border: 0;
    font-weight: bold;
    font-size: 14px;
    color: #FFFFFF;
    cursor: pointer;
    width: 200px;
  margin-top: 15px;
}
.update form input[type="submit"]:hover {
    background-color: #32a367;
}
.delete .yesno {
    display: flex;
}
.delete .yesno a {
    display: inline-block;
    text-decoration: none;
    background-color: #38b673;
    font-weight: bold;
    color: #FFFFFF;
    padding: 10px 15px;
    margin: 15px 10px 15px 0;
}
.delete .yesno a:hover {
    background-color: #32a367;
}

ไฟล์ create.php

ไฟล์นี้จะประกอบด้วย การเชื่อมต่อตารางฐานข้อมูล การตรวจสอบค่าการบันทึกข้อมูลจากแบบฟอร์ม ว่าเป็นค่าว่างหรือไม่ และส่วนในการแทรก หรือเขียนบันทึกข้อมูลลงตารางฐานข้อมูล โดยใช้ code ภาษาแบบ PDO ซึ่งจะมีความปลอดภัยสูงในการป้องกันการแฮกข้อมูลจากผู้ไม่หวังดี 

<?php
include 'function.php';
$pdo = pdo_connect_mysql();
$msg = '';
// Check if POST data is not empty
if (!empty($_POST)) {
    // Post data not empty insert a new record
    // Set-up the variables that are going to be inserted, we must check if the POST variables exist if not we can default them to blank
    $id = isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != 'auto' ? $_POST['id'] : NULL;
    // Check if POST variable "name" exists, if not default the value to blank, basically the same for all variables
    $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
    $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
    $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
    $class = isset($_POST['class']) ? $_POST['class'] : '';
    $datecreate = isset($_POST['datecreate']) ? $_POST['datecreate'] : date('Y-m-d H:i:s');
    // Insert new record into the student table
    $stmt = $pdo->prepare('INSERT INTO tbl_student VALUES (?, ?, ?, ?, ?, ?)');
    $stmt->execute([$id,$fname,$lname,$phone,$class,$datecreate]);
    // Output message
    $msg = 'Created Successfully!';
}
?>

<?=template_header('Create')?>

<div class="content update">
    <h2>Create student data</h2>
    <form action="create.php" method="post">
        <label for="id">ID</label>
        <label for="fname">fName</label>
        <input type="text" name="id" placeholder="26" value="auto" id="id">
        <input type="text" name="fname" placeholder="John Doe" id="fname">

        <label for="lname">lname</label>
        <label for="phone">Phone</label>
        <input type="text" name="lname" placeholder="johndoe@example.com" id="lname">
        <input type="text" name="phone" placeholder="0817453746" id="phone">

        <label for="class">class</label>
        <label for="datecreate">datecreate</label>
        <input type="text" name="class" placeholder="grade3" id="class">
        <input type="datetime-local" name="datecreate" value="<?=date('Y-m-d\TH:i')?>" id="datecreate">
        <input type="submit" value="Create">
    </form>
    <?php if ($msg): ?>
    <p><?=$msg?></p>
    <?php endif; ?>
</div>

<?=template_footer()?>

ไฟล์ index.php

ไฟล์แสดงผลหน้าแรกของเวบไซต์ ที่จะมีเมนู ในการคลิกและดึงข้อมูลจากตารางมาแสดงผล 

<?php
include 'function.php';
// Your PHP code here.

// Home Page template below.
?>

<?=template_header('Home')?>

<div class="content">
    <h2>Home</h2>
    <p>Welcome to Student database</p>
</div>

<?=template_footer()?> 

ไฟล์ function.php 

จะมี 3 ส่วนหลักๆ ด้วยกัน คือ ส่วนติดต่อกับตารางฐานข้อมูล ส่วนหัวของหน้าเพจ และส่วนท้ายของเพจ

<?php

function pdo_connect_mysql() {
    $DATABASE_HOST = 'localhost';
    $DATABASE_USER = 'root';
    $DATABASE_PASS = '';
    $DATABASE_NAME = 'student_db';
    try {
        return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
    } catch (PDOException $exception) {
        // If there is an error with the connection, stop the script and display the error.
        exit('Failed to connect to database!');
    }
}
function template_header($title) {
echo <<<EOT
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>$title</title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <link rel="styleseet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
    </head>
    <body>
    <nav class="navtop">
        <div>
            <h1>Website Title</h1>
            <a href="index.php"><i class="fas fa-home"></i>Home</a>
            <a href="read.php"><i class="fas fa-address-book"></i>Contacts</a>
        </div>
    </nav>
EOT;
}
function template_footer() {
echo <<<EOT
    </body>
</html>
EOT;
}

?> 

ไฟล์ read.php

เป็น code ในการดึงข้อมูลจากตารางมาแสดงผล ตามหัวข้อที่กำหนด และมีปุ่มคำสั่งในการเรียกแบบฟอร์มในการ add ข้อมูล

<?php
include 'function.php';
// Connect to MySQL database
$pdo = pdo_connect_mysql();
// Get the page via GET request (URL param: page), if non exists default the page to 1
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
// Number of records to show on each page
$records_per_page =5 ;


// Prepare the SQL statement and get records from our contacts table, LIMIT will determine the page
$stmt = $pdo->prepare('SELECT * FROM tbl_student ORDER BY id LIMIT :current_page, :record_per_page');
$stmt->bindValue(':current_page', ($page-1)*$records_per_page, PDO::PARAM_INT);
$stmt->bindValue(':record_per_page', $records_per_page, PDO::PARAM_INT);
$stmt->execute();
// Fetch the records so we can display them in our template.
$contacts = $stmt-> fetchAll(PDO::FETCH_ASSOC);



// Get the total number of contacts, this is so we can determine whether there should be a next and previous button
$num_contacts = $pdo->query('SELECT COUNT(*) FROM tbl_student')->fetchColumn();
?>

<?=template_header('Read')?>

<div class="content read">
    <h2>Read Student contacts</h2>
    <a href="create.php" class="create-contact">Create Contact</a>
    <table>
        <thead>
            <tr>
                <td>id</td>
                <td>fName</td>
                <td>lname</td>
                <td>Phone</td>
                <td>class</td>
                <td>datecreate</td>
                <td></td>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($contacts as $contact): ?>
            <tr>
                <td><?=$contact['id']?></td>
                <td><?=$contact['fname']?></td>
                <td><?=$contact['lname']?></td>
                <td><?=$contact['phone']?></td>
                <td><?=$contact['class']?></td>
                <td><?=$contact['datecreate']?></td>

                <td class="actions">
                    <a href="update.php?id=<?=$contact['id']?>" class="edit"><i class="fas fa-pen fa-xs"></i></a>
                    <a href="delete.php?id=<?=$contact['id']?>" class="trash"><i class="fas fa-trash fa-xs"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="pagination">
        <?php if ($page > 1): ?>
        <a href="read.php"><i class="fas fa-angle-double-left fa-sm"></i></a>
        <?php endif; ?>
        <?php if ($page*$records_per_page < $num_contacts): ?>
        <a href="read.php"><i class="fas fa-angle-double-right fa-sm"></i></a>
        <?php endif; ?>
    </div>
</div>

<?=template_footer()?>


ไฟล์ update ข้อมูล
ในส่วนนี้จะคล้ายๆกับไฟล์ create.php สามารถคัดลอกมาวาง และแก้ไขได้เลย 
กรณีเราต้องการแก้ไข เปลี่ยนแปลงข้อมูล ก็จะใช้ไฟล์นี้เรียกคำสั่งทำงาน ขึ้นมา 
<?php
include 'function.php';
$pdo = pdo_connect_mysql();
$msg = '';
// Check if the contact id exists, for example update.php?id=1 will get the contact with the id of 1
if (isset($_GET['id'])) {
    if (!empty($_POST)) {
        // This part is similar to the create.php, but instead we update a record and not insert
        $id = isset($_POST['id']) ? $_POST['id'] : NULL;
        $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
        $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
        $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
        $class = isset($_POST['class']) ? $_POST['class'] : '';
        $datecreate = isset($_POST['datecreate']) ? $_POST['datecreate'] : date('Y-m-d H:i:s');
        // Update the record
        $stmt = $pdo->prepare('UPDATE tbl_student SET id = ?, fname = ?,lname = ?, phone = ?, class = ?, datecreate = ? WHERE id = ?');
        $stmt->execute([$id, $fname, $lname, $phone, $class, $datecreate, $_GET['id']]);
        $msg = 'Updated Successfully!';
    }
    // Get the contact from the contacts table
    $stmt = $pdo->prepare('SELECT * FROM tbl_student WHERE id = ?');
    $stmt->execute([$_GET['id']]);
    $contact = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$contact) {
        exit('Contact doesn\'t exist with that ID!');
    }
} else {
    exit('No ID specified!');
}
?>

<?=template_header('Read')?>

<div class="content update">
    <h2>Update Contact #<?=$contact['id']?></h2>
    <form action="update.php?id=<?=$contact['id']?>" method="post">
        <label for="id">ID</label>
        <label for="name">Name</label>
        <input type="text" name="id" placeholder="1" value="<?=$contact['id']?>" id="id">
        <input type="text" name="fname" placeholder="John Doe" value="<?=$contact['fname']?>" id="fname">
        <label for="email">Email</label>
        <label for="phone">Phone</label>
        <input type="text" name="lname" placeholder="johndoe@example.com" value="<?=$contact['lname']?>" id="lname">
        <input type="text" name="phone" placeholder="2025550143" value="<?=$contact['phone']?>" id="phone">
        <label for="title">Title</label>
        <label for="created">Created</label>
        <input type="text" name="class" placeholder="Employee" value="<?=$contact['class']?>" id="class">
        <input type="datetime-local" name="datecreate" value="<?=date('Y-m-d\TH:i', strtotime($contact['datecreate']))?>" id="datecreate">
        <input type="submit" value="Update">
    </form>
    <?php if ($msg): ?>
    <p><?=$msg?></p>
    <?php endif; ?>
</div>

<?=template_footer()?>
ไฟล์ delete.php สำหรับการลบข้อมูลออกจากฐานข้อมูล
<?php
include 'function.php';
$pdo = pdo_connect_mysql();
$msg = '';
// Check that the contact ID exists
if (isset($_GET['id'])) {
    // Select the record that is going to be deleted
    $stmt = $pdo->prepare('SELECT * FROM  WHERE id = ?');
    $stmt->execute([$_GET['id']]);
    $contact = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$contact) {
        exit('Contact doesn\'t exist with that ID!');
    }
    // Make sure the user confirms beore deletion
    if (isset($_GET['confirm'])) {
        if ($_GET['confirm'] == 'yes') {
            // User clicked the "Yes" button, delete record
            $stmt = $pdo->prepare('DELETE FROM  WHERE id = ?');
            $stmt->execute([$_GET['id']]);
            $msg = 'You have deleted the contact!';
        } else {
            // User clicked the "No" button, redirect them back to the read page
            header('Location: read.php');
            exit;
        }
    }
} else {
    exit('No ID specified!');
}
?>
<?=template_header('Delete')?>

<div class="content delete">
    <h2>Delete Contact #<?=$contact['id']?></h2>
    <?php if ($msg): ?>
    <p><?=$msg?></p>
    <?php else: ?>
    <p>Are you sure you want to delete contact #<?=$contact['id']?>?</p>
    <div class="yesno">
        <a href="delete.php?id=<?=$contact['id']?>&confirm=yes">Yes</a>
        <a href="delete.php?id=<?=$contact['id']?>&confirm=no">No</a>
    </div>
    <?php endif; ?>
</div>

<?=template_footer()?>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น