แน่นอน! ด้านล่างนี้คือตัวอย่าง **แอปลงทะเบียนสมาชิกเว็บ** ด้วยภาษา **PHP** พร้อมการเชื่อมต่อกับ **ฐานข้อมูล MySQL** อย่างง่าย เหมาะสำหรับการเริ่มต้นเรียนรู้
---
### 🧱 โครงสร้างไฟล์:
```
/register-app/
│
├── db.php
├── register.php
└── success.php
```
---
## 1. `db.php` – เชื่อมต่อฐานข้อมูล
```php
<?php
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
```
---
## 2. `register.php` – ฟอร์มและจัดการการลงทะเบียน
```php
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// ตรวจสอบซ้ำ
$check = $conn->prepare("SELECT id FROM users WHERE email = ?");
$check->bind_param("s", $email);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
echo "อีเมลนี้มีอยู่แล้ว!";
} else {
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute()) {
header("Location: success.php");
exit();
} else {
echo "เกิดข้อผิดพลาดในการลงทะเบียน";
}
}
}
?>
<!-- ฟอร์มลงทะเบียน -->
<form method="POST" action="register.php">
<label>ชื่อผู้ใช้:</label>
<input type="text" name="username" required>
<label>อีเมล:</label>
<input type="email" name="email" required>
<label>รหัสผ่าน:</label>
<input type="password" name="password" required>
<input type="submit" value="ลงทะเบียน">
</form>
```
---
## 3. `success.php` – หน้ายืนยันความสำเร็จ
```php
<!DOCTYPE html>
<html>
<head>
<title>ลงทะเบียนสำเร็จ</title>
</head>
<body>
<h2>สมัครสมาชิกเรียบร้อยแล้ว!</h2>
<a href="register.php">กลับไปหน้าสมัคร</a>
</body>
</html>
```
---
## 4. 🗃� SQL สำหรับสร้างตาราง `users`
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
------------------------------------------------