สำหรับบทความนี้เราจะมาลองเขียนโค้ดดึงข้อมูลจากฐานข้อมูล MySql ด้วยภาษา PHP มาแสดงบนหน้าเว็บเพจ ซึ่งจะใช้ความรู้พื้นฐานที่ได้จากบทความที่แล้วมาประยุกต์ใช้อย่างต่อเนื่อง มาลองกันเลยครับ
ขั้นตอนที่ 1 สร้างไฟล์ใหม่ชื่อ fetch_data.php
ต่อจากบทความที่แล้ว ให้สร้างไฟล์ใหม่ชื่อ fetch_data.php แล้วพิมพ์โค้ดคำสั่งดังนี้
<?php
include 'connect_db.php';
$query="select * from customers limit 50"; // Fetch all the data from the table customers
$result=mysqli_query($conn,$query);
?>
ขั้นตอนที่ 2 แก้ไขไฟล์ index.php
- แก้ไขไฟล์ index.php ให้เป็นดังนี้
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to Insert Form Data In Database using PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row mt-5">
<div class="col-sm mx-1 border border-secondary p-2">
<div class="text-primary">
<h3>บันทึกข้อมูลลงในฐานข้อมูลด้วยภาษา php</h3>
</div>
<form action="insert.php" method="post">
<div class="form-group">
<label>ชื่อ</label>
<input type="text" name="fname" class="form-control">
</div>
<div class="form-group">
<label>นามสกุล</label>
<input type="text" name="lname" class="form-control">
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" name="email" class="form-control">
</div>
<input type="submit" class="btn btn-primary" name="submit" value="save">
</form>
</div>
<div class="col-sm mx-1 border border-secondary p-4">
<div class="page-header">
<h2>รายชื่อลูกค้าที่มีอยู่ในฐานข้อมูล</h2>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<?php include 'fetch_data.php'; ?>
<?php if ($result->num_rows > 0): ?>
<?php while($array=mysqli_fetch_row($result)): ?>
<tr>
<th scope="row"><?php echo $array[0];?></th>
<td><?php echo $array[1];?></td>
<td><?php echo $array[2];?></td>
<td><?php echo $array[3];?></td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="3" rowspan="1" headers="">No Data Found</td>
</tr>
<?php endif; ?>
<?php mysqli_free_result($result); ?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
จะได้หน้าตาของเว็บประมาณนี้

ขั้นตอนที่ 3 แก้ไขไฟล์ insert.php
- แก้ไขไฟล์ insert.php ให้เป็นดังนี้
<?php
include 'connect_db.php';
if(!isset($_POST['save']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$sql = "INSERT INTO customers (fname,lname,email)
VALUES ('$fname','$lname','$email')";
if (mysqli_query($conn, $sql)) {
header("Location:index.php");
} else {
echo "เกิดข้อผิดพลาด: " . $sql . ":-" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
จะได้หน้าตาของแบบฟอร์มประมาณนี้

ลองทดสอบบันทึกข้อมูล จะได้ผลลัพธ์ดังนี้
