PHP ย่อมาจาก PHP Hypertext Preprocessor
เป็นภาษาคอมพิวเตอร์ที่มีลักษณะของการประมวลผลที่เครื่องให้บริการ (Server) หรือที่เรียกกันว่า Server-Side คือ คำสั่งต่างๆ จะเก็บอยู่ในไฟล์ที่เรียกว่า สคริปต์ (Scrip) และเวลาใช้งานต้องอาศัยตัวแปรชุดคำสั่ง ซึ่งทำงานโดยสั่งงานจากเว็บเพจ ไปประมวลผลที่ Web Server จากนั้น ก็จะ respone กลับมาที่ web Browser ของเครื่อง Client ปัจจุบันนั้น PHP ถูกพัฒนาอย่างต่อเนื่อง จนถึง Version 8
มี CMS หลายตัวที่ใช้ PHP เป็นโครงสร้างหลัก ยกตัวอย่าง WordPress,Joomla,Drupal ใน Version ใหม่ ๆ PHP ก็ได้มีการปรับในเรื่องของความเร็ว และ ความปลอดภัยเพิ่มขึ้น
ข้อดีคือ
ข้อเสีย
OOP (Object-Oriented Programing) คือการเขียนโปรแกรมเชิงวัตถุ
การเขียนโปรแกรมเชิงวัตถุ คือหนึ่งในรูปแบบการเขียนโปรแกรมคอมพิวเตอร์ ที่ถูกออกแบบมาให้โค้ดที่เราเขียนมีแบบแผนที่เหมาะสมพร้อมใช้ในการพัฒนาที่ซับซ้อนได้ ประโยชน์ของการเขียนแบบ OOP นั้น ก็เพื่อช่วยเพิ่มความปลอดภัยที่มากขึ้น เพื่อช่วยลดข้อผิดพลาดของการเขียน Code ลงและทำให้งานไปเร็วขึ้นได้
ถ้าเราเปรียบ Class เหมือนรถยนต์ โดยมีคุณสมบัติ เช่น ยี่ห้อรถ สี เราสามารถกำหนดตัวแปรเช่น $bland,$color เพื่อเก็บค่าของคุณสมบัติเหล่านี้ เมื่อ Object แต่ละอย่าง ถูกสร้างขึ้น Object จะสืบทอดคุณสมบัติและพฤติกรรมทั้งหมดจาก Class
การกำหนด Class จะตั้งชื่อ Class ตามด้วยปีกกาเปิดปิด
class Car {
}
จาก Code ด้านล่างนี้เราจะประกาศ Class ชื่อ Car และมี properties อยู่ 2 ชนิด และมี methods 2 ตัว คือ setBrand(),getBrand() เอาไว้ตั้งค่าและดึงค่าคุณสมบัติ ใน Class ตัวแปรจะเรียกว่า Properties และ function เรียกว่า Methods
class Car {
// Properties
public $brand;
public $color;
// Methods
function setBrand($brand) {
$this->brand= $brand;
}
function getBrand() {
return $this->brand;
}
}
กำหนดเรียกใช้งาน Objects ของ Class โดยใช้ new ในการเรียกใช้ ตัวอย่าง $Toyota = new Car(); การใช้ $this ใน PHP เป็นการ อ้างอิงถึง methods ภายใน Class
class Car {
// Properties
public $brand;
public $color;
// Methods กำหนดค่า ยี่ห้อรถ
function setBrand($brand) {
$this->brand= $brand;
}
// Methods คืนค่า ยี่ห้อรถ
function getBrand() {
return $this->brand;
}
}
$Toyota = new Car();
$Honda = new Car();
$Toyota->setBrand('Toyota');
$Honda->setBrand('Honda');
echo $Toyota->getBrand();
echo "<br>";
echo $Honda->getBrand();
ใน Code ด้านล่างนี้ เราจะลองเรียก ใช้ Methods ที่กำหนดค่าสี
class Car {
// Properties
public $brand;
public $color;
// Methods กำหนดค่า ยี่ห้อรถ
function setBrand($brand) {
$this->brand= $brand;
}
// Methods คืนค่า ยี่ห้อรถ
function getBrand() {
return $this->brand;
}
// Methods กำหนดค่า สีรถ
function setColor($color) {
$this->color= $color;
}
// Methods คืนค่า สีรถ
function getColor() {
return $this->color;
}
}
$Toyota = new Car();
$Toyota->setBrand('Toyota');
$Toyota->setColor('สีบรอนซ์เทา');
echo $Toyota->getBrand();
echo "<br>";
echo $Toyota->getColor();
ใน Properties ที่ชื่อ $brand เราสามารถกำหนดค่าได้ 2 ทาง
// วิธีที่หนึ่งกำหนดผ่าน Methods โดย Set ค่าไปที่ Properties
class Car {
public $brand;
function setBrand($brand) {
$this->brand = $brand;
}
}
$Toyota = new Car();
$Toyota->setBrand("Toyota");
echo $Toyota->brand;
// อีกวิธีคือ Set ค่าไปที่ Properties ได้เลย
class Car {
public $brand;
}
$Toyota = new Car();
$Toyota->brand = "Toyota";
echo $Toyota->brand;
Constructor เป็น method เริ่มต้น เมื่อมีการสร้าง Object จาก Class จะเริ่มทำงานทันที method construct เริ่มต้นด้วยขีดล่างสองตัว (__)
class Car {
public $brand;
public $color;
function __construct($brand) {
$this->brand = $brand;
}
function getBrand() {
return $this->brand;
}
}
$brand = new Car("BMW");
echo $brand->getBrand();
อีกตัวอย่าง
class Car {
public $brand;
public $color;
function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
function getBrand() {
return $this->brand;
}
function getColor() {
return $this->color;
}
}
$car = new Car("BMW", "สีขาวมุก");
echo $car->getBrand();
echo "
";
echo $car->getColor();
__destruct วัตถุประสงค์หลักของ destructor คือการทำลายหรือลบวัตถุออกจากหน่วยความจำหลังจากที่โปรแกรมหยุดทำงานหรือกระบวนการสิ้นสุดลง
class Car {
public $brand;
public $color;
function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
function __destruct() {
echo "{$this->brand} {$this->color} ";
}
}
$car = new Car("BMW", "สีขาวมุก");
คุณสมบัติของ Static สามารถเรียกได้โดยตรง - โดยไม่ต้องสร้าง instance ของ Class
class FirstClass {
public static $website = "deedev.com";
}
echo FirstClass::$website;
วิธีเรียกใช้งานเพียงใช้ double colon (::) ตามด้วยชื่อตัวแปร ถ้าหากอยู่ภายใน Class ก็เรียกผ่าน self:: ได้เลย
class PriceProduct {
public static $value=100;
public function staticNotVat() {
return $this->priceNotVat(self::$value);
}
public function staticSumVat() {
return $this->priceVat(self::$value);
}
//แยกราคาออกจากแวท
public function priceNotVat($price)
{
// $price = ราคารวมภาษี
return round((($price)-round($price/1.07,4)*0.07),2);
}
//แยก vat ออกจากราคา
public function priceVat($price)
{
return round((round($price/1.07,4)*0.07),2);
}
}
$price = new PriceProduct();
echo "ราคายังไม่รวม Vat ".$price->staticNotVat()." บาท
";
echo " Vat ".$price->staticSumVat()." บาท
";
echo " รวม ".PriceProduct::$value." บาท
";
public คือ property หรือ method ที่เป็นค่าเริ่มต้น สามารถเรียกได้จากทุกที่
class Car {
// กำหนดตัวแปรแบบ public
public $brand;
// Method แบบ public
public function getBrand($brand) {
return $brand;
}
}
$car = new Car();
echo $car->getBrand("Toyota");
echo "<br>";
echo $car->brand="Honda";
protected คือ property หรือ method ที่สามารถเข้าถึงได้จากภายในคลาสย่อย ที่เกิดจากการถ่ายทอดคุณสมบัติ(Inheritance) เท่านั้น
private คือ property หรือ method ที่สามารถเข้าถึงได้จากคลาสตนเองเท่านั้น
class Car {
// กำหนดตัวแปรแบบ private
private $brand;
// กำหนดตัวแปรแบบ protected
protected $color;
// Method แบบ protected
protected function getColor($color) {
return $color;
}
private function getBrand($brand) {
return $brand;
}
}
class CarDetails extends Car{
// กำหนดตัวแปรแบบ public
public $type;
// Method แบบ public
public function showColor($color) {
return $this->getColor($color);
}
public function showBrand($brand)
{
return $this->getBrand($brand);
}
}
$color = new CarDetails;
// กำหนดค่าให้กับ public property ของ main class
echo $color->type = 'รถเก๋ง'; // ok
//
echo $color->showColor('สีขาวมุก');
// จะไม่แสดงผล เนื่องจากเราไปเรียก private ใน Class Car อีกที
echo $color->showBrand('จากค่าย BMW');
ตัวอย่าง Work Shop สร้าง Form Validate Jquery และเรียกใช้งาน Functions ภายในหน้าเดียวกัน
แทรก Code PHP - Class CheckVat โดยมี 2 method ทำหน้าที่แยก กันดังนี้ priceNotVat ทำหน้าที่แยกราคาต้นทุนออกจากภาษี
priceVat ทำหน้าที่แยกภาษีมูลค่าเพิ่ม 7 % ออกจาก ราคาเต็ม
class CheckVat
{
//แยกราคาออกจากแวท
public function priceNotVat($price)
{
return round((($price)-round($price/1.07,4)*0.07),2);
}
//แยกแวทออกจากราคา
public function priceVat($price)
{
return round((round($price/1.07,4)*0.07),2);
}
}
แทรก Code javascripts โดยจะเป็นการบังคับ price-form ให้กรอกข้อมูลที่เป็นตัวเลขเท่านั้น
<script>
$(document).ready(function() {
$("#price-form").validate({
rules: {
price: {
required: true,
number: true
},
},
messages: {
price: 'ใส่ราคาเต็มเป็นตัวเลข',
},
submitHandler: function(form) {
return true;
}
});
});
</script>
Code เต็ม ลองนำไปเล่นได้ครับ
<!DOCTYPE html>
<html lang="en">
<head>
<title>ตัวอย่าง Work Shop สร้าง Form Validate Jquery และเรียกใช้งาน Functions</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<style>
.error{
color:red;
}
</style>
</head>
<body>
<?php
class CheckVat
{
//แยกราคาออกจากแวท
public function priceNotVat($price)
{
// $price = ราคารวมภาษี
return round((($price)-round($price/1.07,4)*0.07),2);
}
//แยกแวทออกจากราคา
public function priceVat($price)
{
return round((round($price/1.07,4)*0.07),2);
}
}
$pr=new CheckVat();
$price =0;
if(isset($_POST['price'])){
$price=$_POST['price'];
}
?>
<div class="jumbotron text-center">
<h1>PHP OOP By Deedev.com</h1>
<p> ตัวอย่าง Work Shop สร้าง Form Validate Jquery และเรียกใช้งาน Functions </p>
</div>
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<form class="card p-2" id="price-form" action="/workshop/exmp1.php" method="POST" novalidate>
<div class="form-group">
<input type="number" class="form-control" name="price" placeholder="ใส่ราคาเต็มรวมภาษีมูลค่าเพิ่ม">
</div>
<button type="submit" class="btn btn-primary">คำนวณ</button>
</form>
<h5 class="text-right"> ราคายังไม่รวม Vat : <?php echo $pr->priceNotVat($price); ?> บาท</h5>
<h5 class="text-right"> Vat : <?php echo $pr->priceVat($price); ?> บาท</h5>
<h5 class="text-right"> รวม : <strong class="text-danger"> <?php echo $price; ?> </strong> บาท</h5>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#price-form").validate({
rules: {
price: {
required: true,
number: true
},
},
messages: {
price: 'ใส่ราคาเต็มเป็นตัวเลข',
},
submitHandler: function(form) {
return true;
}
});
});
</script>
</body>
</html>
ใน Work Shop นี้เราจะมา สร้าง form เพื่อส่งข้อมูลไปบันทึกลงใน database กันครับ
<!DOCTYPE html>
<html lang="en">
<head>
<title>ตัวอย่าง Work Shop สร้าง form และ สร้าง class เพื่อเพิ่มข้อมูลลง Database</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<style>
.error{
color:red;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>PHP OOP</h1>
<p> ตัวอย่าง Work Shop สร้าง form และ สร้าง class เพื่อเพิ่มข้อมูลลง Database </p>
</div>
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<form class="card p-2" id="price-form" action="/workshop/insert.php" method="POST" novalidate>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">โปรดระบุชื่อ</span>
</div>
<input type="text" class="form-control" placeholder="ชื่อ" name="FirstName">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">โปรดระบุนามสกุล</span>
</div>
<input type="text" class="form-control" placeholder="สกุล" name="LastName">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">โปรดระบุเบอร์มือถือ</span>
</div>
<input type="text" class="form-control" placeholder="เบอร์มือถือ" name="MobileNumber">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">โปรดระบุ Email</span>
</div>
<input type="email" class="form-control" placeholder="Email" name="Email">
</div>
<button type="submit" class="btn btn-primary">บันทึก</button>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#price-form").validate({
rules: {
FirstName: {
required: true,
},
LastName: {
required: true,
},
MobileNumber: {
required: true,
number:true,
min:10,
},
Email: {
required: true,
email:true
},
},
messages: {
FirstName: 'โปรดระบุชื่อ',
LastName: 'โปรดระบุนามสกุล',
MobileNumber: 'โปรดระบุเบอร์มือถือเป็นตัวเลข',
Email: 'โปรดระบุ Email ให้ถูกต้อง',
},
submitHandler: function(form) {
return true;
}
});
});
</script>
</body>
</html>
CREATE TABLE `member` (
`MemberID` int(11) NOT NULL,
`FirstName` varchar(100) NOT NULL,
`LastName` varchar(100) NOT NULL,
`MobileNumber` int(11) NOT NULL,
`Email` varchar(100) NOT NULL,
`CreateDate` datetime NOT NULL,
`UpdateDate` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
class connectDB {
public static function connectmysql()
{
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "profile";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
return die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
require 'connectDB.php';
if(!empty($_POST)){
$v=$_POST;
$cn=connectDB::connectmysql();
$sql = "INSERT INTO member (FirstName, LastName, MobileNumber,Email,CreateDate)
VALUES ('".$v['FirstName']."'
,'".$v['LastName']."'
,'".$v['MobileNumber']."'
,'".$v['Email']."'
,'".date('Y-m-d H:i:s')."')";
if ($cn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $cn->error;
}
$cn->close();
}
ใน Work Shop นี้จะต่อ ยอดจาก Work Shop ที่แล้ว แต่จะเป็นการนำข้อมูลมาแสดงในรูปแบบ Datatables
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<style>
.error{
color:red;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>PHP OOP</h1>
<p> ตัวอย่าง Work Shop นำข้อมูลมาแสดงด้วย Datatables แบบ ปกติ </p>
</div>
<?php require 'connectDB.php';
$sql="select * from member";
// functions แสดงข้อมูลแบบ Array
$obj = connectDB::getArr($sql);
?>
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<table id="member" class="table table-striped table-bordered table-hover" >
<thead>
<tr>
<th style="widt:10px">#</th>
<th>ชื่อ</th>
<th>สกุล</th>
<th>เบอร์มือถือ</th>
<th>Email</th>
<th>เป็นสมาชิกเมื่อ</th>
</tr>
</thead>
<?php
foreach ($obj as $k => $v) {
echo '
<tr>
<td>'.($k+1).'</td>
<td>'.$v['FirstName'].'</td>
<td>'.$v['LastName'].'</td>
<td>'.$v['MobileNumber'].'</td>
<td>'.$v['Email'].'</td>
<td>'.$v['CreateDate'].'</td>
</tr>
';
}
?>
</table>
<hr>
<?php
// functions แสดงข้อมูลแบบ Object
$objT = connectDB::getObj($sql);
?>
<table id="memberObj" class="table table-striped table-bordered table-hover" >
<thead>
<tr>
<th style="widt:10px">#</th>
<th>ชื่อ</th>
<th>สกุล</th>
<th>เบอร์มือถือ</th>
<th>Email</th>
<th>เป็นสมาชิกเมื่อ</th>
</tr>
</thead>
<?php
foreach ($objT as $k => $v) {
echo '
<tr>
<td>'.($k+1).'</td>
<td>'.$v->FirstName.'</td>
<td>'.$v->LastName.'</td>
<td>'.$v->MobileNumber.'</td>
<td>'.$v->Email.'</td>
<td>'.$v->CreateDate.'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#member").DataTable();
$("#memberObj").DataTable();
});
</script>
</body>
</html>
ที่ไฟล์ connectDB.php เพิ่ม method สำหรับ query ข้อมูลออกมาเป็น ทั้งแบบ array และ object
นำ Try ... Catch มาใช้ เพื่อดักจับข้อผิดพลาด (Exception) และแก้ไขสิ่งเหล่านั้น เพื่อป้องกันการทำงานที่ผิดพลาดของโปรแกรม และสร้างทางเลือกสำหรับการทำงานหากพบข้อผิดพลาดในลักษณะต่าง ๆ
public static function connectmysql()
{
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "profile";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
return die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
/*
|--------------------------------------------------------------------------
| เป็นการ query แล้วเรียกแสดงข้อมูลแบบ array ตัวอย่าง $obj['FirstName']
|--------------------------------------------------------------------------
*/
public static function getArr($sql)
{
try {
$result_array = array();
$cn=self::connectmysql();
if($cn)
{
$result = mysqli_query($cn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$result_array[] = $row;
}
mysqli_close($cn);
return $result_array;
}
}
}
catch (\Exception $e) {
return $e->getMessage();
}
}
/*
|--------------------------------------------------------------------------
| เป็นการ query แล้วเรียกแสดงข้อมูลแบบ object ตัวอย่าง $obj->FirstName
|--------------------------------------------------------------------------
*/
public static function getObj($sql)
{
try {
$result_object = array();
$result_array = array();
$cn=self::connectmysql();
if($cn)
{
$result = mysqli_query($cn, $sql);
while($row = mysqli_fetch_assoc($result)) {
array_push($result_array,$row);
foreach($result_array as $k => $v)
{
$result_object[$k] = (object) $v;
}
}
mysqli_close($cn);
return $result_object;
}
}
catch (\Exception $e) {
return $e->getMessage();
}
}
เพิ่มส่วน code javascript
$(document).ready(function() {
$("#member").DataTable();
});
ใน workshop นี้ จะเป็นการต่อยอดจาก workshop ก่อนหน้านี้ ซึ่งจะเป็นการนำข้อมูลมาแสดง โดยใช้ datatable แบบ Server Side ข้อดีของแบบ server side นั้น กรณีข้อมูลของเรามีจำนวนมาก จะช่วยทำให้ ดึงข้อมูลมาแสดงได้เร็วขึ้น
<!DOCTYPE html>
<html lang="en">
<head>
<title> ตัวอย่าง Work Shop นำข้อมูลมาแสดงด้วย Datatables แบบ Server Side </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<style>
.error{
color:red;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>PHP OOP</h1>
<p> ตัวอย่าง Work Shop นำข้อมูลมาแสดงด้วย Datatables แบบ Server Side </p>
</div>
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<table id="member" class="table table-striped table-bordered table-hover" >
<thead>
<tr>
<th style="widt:10px">#</th>
<th>ชื่อ</th>
<th>สกุล</th>
<th>เบอร์มือถือ</th>
<th>Email</th>
<th>เป็นสมาชิกเมื่อ</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#member").DataTable({
"autoWidth": true,
pageLength: 10,
serverSide: true,
processing: false,
bDestroy: true,
ajax: {
type:"POST",
url: 'memberjson.php'
},
'columns': [
{
className:'text-center',
data: "RowID",
},
{
className:'text-center',
data:'FirstName'
},
{
className:'text-center',
data:'LastName'
},
{
className:'text-center',
data:'MobileNumber'
},
{
className:'text-center',
data:'Email'
},
{
className:'text-center',
data:'CreateDate'
},
],
});
});
</script>
</body>
</html>
จะมีส่วนที่เพิ่มเข้ามาส่วนที่เป็น javascript ที่เรียกใช้งาน datatable แบบ ajax
$(document).ready(function() {
$("#member").DataTable({
"autoWidth": true,
pageLength: 10,
serverSide: true,
processing: false,
bDestroy: true,
ajax: {
type:"POST",
url: 'memberjson.php'
},
'columns': [
{
className:'text-center',
data: "RowID",
},
{
className:'text-center',
data:'FirstName'
},
{
className:'text-center',
data:'LastName'
},
{
className:'text-center',
data:'MobileNumber'
},
{
className:'text-center',
data:'Email'
},
{
className:'text-center',
data:'CreateDate'
},
],
});
});
/*
|--------------------------------------------------------------------------
| เรียกใช้ connectDB
|--------------------------------------------------------------------------
*/
require 'connectDB.php';
/*
|--------------------------------------------------------------------------
| ตั้งค่า POST ที่ถูกส่งมาจาก datatable
|--------------------------------------------------------------------------
*/
$order_index = $_POST['order'][0]['column'];
$start = $_POST['start'];
if($start !=0)
{
$start = $start+1;
$length=$_POST['start'] + $_POST['length'];
}else{
$length= $_POST['length'];
}
$page_size = $length;
$keyword = trim($_POST['search']['value']);
$param['column'] = $_POST["columns"][''.$order_index.'']['data'];
$dir = $_POST['order'][0]['dir'];
/*
|--------------------------------------------------------------------------
| เช็คว่ามีการ search เข้ามาหรือไม่
|--------------------------------------------------------------------------
*/
$sqlx="";
if($keyword)
{
$sqlx="where (FirstName Like '%".$keyword."%' OR LastName Like '%".$keyword."%' OR MobileNumber Like '%".$keyword."%' OR Email Like '%".$keyword."%' ) ";
}
/*
|--------------------------------------------------------------------------
| เขียน query และส่ง ไปที่ connectDB::getArr
|--------------------------------------------------------------------------
*/
$sql="
select *,row_number() over (order by MemberID desc) AS RowID from member
".$sqlx." ";
$obj = connectDB::getArr($sql);
/*
|--------------------------------------------------------------------------
| ใส่เงื่อนไขให้ query ตัวอย่าง limit 0,10 คือ ให้แสดง row ที่ 0 - 10
|--------------------------------------------------------------------------
*/
$sql .="LIMIT ".$start.",".$page_size;
$objOne = connectDB::getArr($sql);
/*
|--------------------------------------------------------------------------
| เช็คจำนวน row เพื่อ respone กลับไปให้ datatable
|--------------------------------------------------------------------------
*/
$total=0;
$totalOne=0;
if(!empty($obj))
{
$total = count($obj);
$totalOne = count($objOne);
}
/*
|--------------------------------------------------------------------------
| ตั้งค่ารูปแบบข้อมูลกับไป ให้ datatable
|--------------------------------------------------------------------------
*/
$data['draw'] = $_POST['draw'];
$data['recordsTotal'] = $totalOne;
$data['recordsFiltered'] = $total;
$data['data'] = $objOne;
$data['error'] = '';
echo json_encode($data);
class connectDB{
public static function connectmysql()
{
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "profile";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
return die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
/*
|--------------------------------------------------------------------------
| เป็นการ query แล้วเรียกแสดงข้อมูลแบบ array ตัวอย่าง $obj['FirstName']
|--------------------------------------------------------------------------
*/
public static function getArr($sql)
{
try {
$result_array = array();
$cn=self::connectmysql();
if($cn)
{
$result = mysqli_query($cn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$result_array[] = $row;
}
mysqli_close($cn);
return $result_array;
}
}
}
catch (\Exception $e) {
return $e->getMessage();
}
}
/*
|--------------------------------------------------------------------------
| เป็นการ query แล้วเรียกแสดงข้อมูลแบบ object ตัวอย่าง $obj->FirstName
|--------------------------------------------------------------------------
*/
public static function getObj($sql)
{
try {
$result_object = array();
$result_array = array();
$cn=self::connectmysql();
if($cn)
{
$result = mysqli_query($cn, $sql);
while($row = mysqli_fetch_assoc($result)) {
array_push($result_array,$row);
foreach($result_array as $k => $v)
{
$result_object[$k] = (object) $v;
}
}
mysqli_close($cn);
return $result_object;
}
}
catch (\Exception $e) {
return $e->getMessage();
}
}
}