PHP DataObject (Syntax)


 

Connect Database - เชื่มต่อฐานข้อมูล

ob_start();
session_start(); //เรื่มต้น session

$db_name = "database_name"; //ชื่อฐานข้อมูล
$db_host = "localhost";
$db_user = "root"; //ชื่อuser
$db_pass = "1234@#+"; //ชื่อรหัสผ่าน

try{
  $db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
  $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db_con->exec("set names utf8");
}
catch(PDOException $e){
  echo $e->getMessage();
}

Insert Syntax - เพิ่มข้อมูล

$stm = $db_con->prepare("INSERT INTO table_name (col_1, col_2) VALUES (:col_1, :col_2)");
$stm->bindParam("col_1", $_POST['col_1']);
$stm->bindParam("col_2", $_POST['col_2']);
  
$stm->execute();

Update Syntax - เปลี่ยนแปลงข้อมูล

$stm = $db_con->prepare("UPDATE table_name SET col_1 = :col_1, col_2 = :col_2 WHERE id = :id");
$stm->bindParam("col_1", $_POST['col_1']);
$stm->bindParam("col_2", $_POST['col_2']);
$stm->bindParam("id", $_GET['id']);

$stm->execute();

Delete Syntax

$stm = $db_con->prepare("DELETE FROM table_name WHERE id = :id ");
$stm->bindParam(':id', $_GET["id"]);

$result = $stm->execute();

Select Syntax - ดึงข้อมูลแบบไม่มีเงื่อนไข

$stmt = $db_con->prepare("SELECT * FROM table_name ORDER BY id DESC");
$stmt->execute();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)) {
  echo $rows['id'];
}

Select Syntax - ดึงข้อมูลแบบมีเงื่อนไข

$stmt = $db_con->prepare("SELECT * FROM table_name WHERE id = :id ORDER BY id DESC");
$stm->bindParam(':id', $_GET["id"]);

$stmt->execute();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)) {
  echo $rows['id'];
}

Select Syntax - การเรียกข้อมูล 1 แถว

$stmt = $db_con->prepare("SELECT * FROM table_name WHERE id = :id ");
$stmt->bindParam(':id', $_GET["id"]);

$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
echo $rows['id'];
 

Select Syntax - ดึงข้อมูลแสดงผลในรูปแบบ JSON (จะใช้สำหรับการส่งข้อมูลในรูปแบบของ API)

$response = array();
$stmt = $db_con->prepare("SELECT * FROM table_name ORDER BY id DESC");
$stmt->execute();
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $response[] = $rows;
}

echo json_encode($response);
086-2887987
Line Official
Facebook Messenger
Twitter