ฝึกเขียนภาษา PHP ระบบลงทะเบียนข้อมูลและ Login

ให้ดาวโหลดและติดตั้ง XAMPP เพื่อใช้งานกับภาษา PHP scripts. ลิงค์สำหรับดาวโหลด XAMPP server https://www.apachefriends.org/index.html. เปิดหน้าต่างควบคุม  XAMPP's Cและเรียกใช้งาน  Apacheกับ กับ MySQL. รวมทั้ง Bootstrap โดยไปที่ลิค์  https://getbootstrap.com/ .

สร้างฐานข้อมูล 

เปิดไปที่ [i.e. http://localhost/phpmyadmin] สร้างฐานข้อมูล db_login.

สร้างตารางขึ้นมาเก็บข้อมูล โดยแท็บ SQL  copy/paste ตามตัวอย่างด้านล่าง . คลิกปุ่มคำสั่ง  Go เพื่อสร้างตาราง.

  1.  
  2. CREATE TABLE `member` (
  3. `firstname` varchar(50) NOT NULL,
  4. `lastname` varchar(50) NOT NULL,
  5. `username` varchar(30) NOT NULL,
  6. `password` varchar(12) NOT NULL



สร้างไฟล์ชื่อ con.php เพื่อเชื่อมต่อกับฐานข้อมูล
  1. <?php
  2. $db_username = 'root';
  3. $db_password = '';
  4. $conn = new PDO( 'mysql:host=localhost;dbname=db_login', $db_username, $db_password );
  5. if(!$conn){
  6. die("Fatal Error: Connection Failed!");
  7. }
  8. ?>



สร้างไฟล์ index.php เพื่อเป็นหน้าแบบฟอร์ม สำหรับการ Login
  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  7. </head>
  8. <body>
  9. <nav class="navbar navbar-default">
  10. <div class="container-fluid">
  11. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  12. </div>
  13. </nav>
  14. <div class="col-md-3"></div>
  15. <div class="col-md-6 well">
  16. <h3 class="text-primary">PHP - PDO Login and Registration</h3>
  17. <hr style="border-top:1px dotted #ccc;"/>
  18. <div class="col-md-2"></div>
  19. <div class="col-md-8">
  20. <?php if(isset($_SESSION['message'])): ?>
  21. <div class="alert alert-<?php echo $_SESSION['message']['alert'] ?> msg"><?php echo $_SESSION['message']['text'] ?></div>
  22. <script>
  23. (function() {
  24. // removing the message 3 seconds after the page load
  25. setTimeout(function(){
  26. document.querySelector('.msg').remove();
  27. },3000)
  28. })();
  29. </script>
  30. <?php
  31. endif;
  32. // clearing the message
  33. unset($_SESSION['message']);
  34. ?>
  35. <form action="login_query.php" method="POST">
  36. <h4 class="text-success">Login here...</h4>
  37. <hr style="border-top:1px groovy #000;">
  38. <div class="form-group">
  39. <label>Username</label>
  40. <input type="text" class="form-control" name="username" />
  41. </div>
  42. <div class="form-group">
  43. <label>Password</label>
  44. <input type="password" class="form-control" name="password" />
  45. </div>
  46. <br />
  47. <div class="form-group">
  48. <button class="btn btn-primary form-control" name="login">Login</button>
  49. </div>
  50. <a href="registration.php">Registration</a>
  51. </form>
  52. </div>
  53. </div>
  54. </body>
  55. </html>

สร้างไฟล์ลงทะเบียนผู้ใช้งาน register_query.php
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['register'])){
  5. if($_POST['firstname'] != "" || $_POST['username'] != "" || $_POST['password'] != ""){
  6. try{
  7. $firstname = $_POST['firstname'];
  8. $lastname = $_POST['lastname'];
  9. $username = $_POST['username'];
  10. // md5 encrypted
  11. // $password = md5($_POST['password']);
  12. $password = $_POST['password'];
  13. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  14. $sql = "INSERT INTO `member` VALUES ('', '$firstname', '$lastname', '$username', '$password')";
  15. $conn->exec($sql);
  16. }catch(PDOException $e){
  17. echo $e->getMessage();
  18. }
  19. $_SESSION['message']=array("text"=>"User successfully created.","alert"=>"info");
  20. $conn = null;
  21. header('location:index.php');
  22. }else{
  23. echo "
  24. <script>alert('Please fill up the required field!')</script>
  25. <script>window.location = 'registration.php'</script>
  26. ";
  27. }
  28. }
  29. ?>

สร้างไฟล์ทำหน้าที่ตรวจสอบในฐานข้อมูลว่ามีชื่อผู้ใช้งานในระบบหรือไม เพื่อให้สิทธิในการ Login
  1. <?php
  2.  
  3. require_once 'conn.php';
  4.  
  5. if(ISSET($_POST['login'])){
  6. if($_POST['username'] != "" || $_POST['password'] != ""){
  7. $username = $_POST['username'];
  8. $password = $_POST['password'];
  9. $sql = "SELECT * FROM `member` WHERE `username`=? AND `password`=? ";
  10. $query = $conn->prepare($sql);
  11. $query->execute(array($username,$password));
  12. $row = $query->rowCount();
  13. $fetch = $query->fetch();
  14. if($row > 0) {
  15. $_SESSION['user'] = $fetch['mem_id'];
  16. header("location: home.php");
  17. } else{
  18. echo "
  19. <script>alert('Invalid username or password')</script>
  20. <script>window.location = 'index.php'</script>
  21. ";
  22. }
  23. }else{
  24. echo "
  25. <script>alert('Please complete the required field!')</script>
  26. <script>window.location = 'index.php'</script>
  27. ";
  28. }
  29. }
  30. ?>


สร้างไฟล์ Logout.php เพื่อ จบการทำงาน
  1. <?php
  2. header('location: index.php');
  3. ?>

PHP MySQL Database

 การเขียนภาษา PHP สามารถเชื่อมต่อการทำงานกับฐานข้อมูล MySQL ระบบฐานข้อมูลยอดนิยมที่พัฒนาออกมาใช้งานกับ PHP

What is MySQL?

  • MySQL is a database system used on the web
  • MySQL is a database system that runs on a server
  • MySQL is ideal for both small and large applications
  • MySQL is very fast, reliable, and easy to use
  • MySQL uses standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use
  • MySQL is developed, distributed, and supported by Oracle Corporation
  • MySQL is named after co-founder Monty Widenius's daughter: 
ข้อมูลใน MySQL จะเก็บในตาราง มีข้อมูลเป็นแถวและคอลัมน์ ฐานข้อมูลนิยมใช้ในการเก็บข้อมูล 
  • Employees
  • Products
  • Customers
  • Orders
ฐานข้อมูล MySQL จะทำงานได้บนระบบปฏิบัติการ windows และ Linux
ถ้าเราไม่มี PHP server  MySQL Database, สามารถดาวโหลด : http://www.mysql.com

ระบบฐานข้อมูล MYSQL มีการนำไปใช้งานกับฐานข้อมูลขนาดใหญ่เช่น Facebook, Twitter, and Wikipedia เป็นต้น

การเชื่อมต่อฐานข้อมูล MySQL 
จะสามารถเชื่อมต่อได้ 2 ลักษณะ คือ 

PHP 5 and later can work with a MySQL database using:

  • MySQLi extension (the "i" stands for improved)
  • PDO (PHP Data Objects)
การเชื่อมต่อทั้ง 2 แบบ ใช้งานได้เช่นกัน แต่แบบ PDO จะสะดวกมากกว่า ถ้าในอนาคตจะมีการเปลี่ยนแปลงรูปแบบฐานข้อมูลจาก Mysql ไปใช้ระบบอื่นๆ เพราะจะรองรับการเปลี่ยนไปใช้งานระบบฐานข้อมูลอื่นๆ กว่า 12 ชนิด

Open a Connection to MySQL

ก่อนจะทำงานกับ ฐานข้อมูลจะต้อง มีการเชื่อมต่อกับฐานข้อมูล 

Example (MySQLi Object-Oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
------------------------

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
------------------

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
  $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

คำสั่งในการปิดการเชื่อมต่อ แต่ละแบบ 
$conn->close();
mysqli_close($conn);
$conn = null;
-------------------------
การสร้างฐานข้อมูล Create a MySQL Database Using MySQLi and PDO

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
  echo "Database created successfully";
else {
  echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
  echo "Database created successfully";
else {
  echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
  $conn = new PDO("mysql:host=$servername", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "CREATE DATABASE myDBPDO";
  // use exec() because no results are returned
  $conn->exec($sql);
  echo "Database created successfully<br>";
catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>