PHP PDO

 

PHP PDO

    PDO (PHP DataObject) คือ Extension ของภาษา PHP ซึ่งการเขียนแบบ PDO นี้สามารถนำไปใช้กับฐานข้อมูลได้หลาย ๆ แบบ เช่น MySQL, ORACLE ซึ่งการเขียนแบบ PDO ไม่ต้องปรับคำสั่งเวลาเปลี่ยนชนิด DATABASE ซึ่งทำให้มีความยืดหยุ่นมากยิ่งขึ้น ตัวอย่างการเขียน PHP PDO 

 

การเชื่อมต่อฐานข้อมูล

$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();

}

การเพิ่มข้อมูล

$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();

การอัพเดทข้อมูล

$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();

การลบข้อมูล

 

$stm = $db_con->prepare("DELETE FROM table_name WHERE id = :id ");

$stm->bindParam(':id', $_GET["id"]);

$result = $stm->execute();

การ select แบบมีเงือนไข

$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 แบบหนึ่งแถว

$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 แล้วแปลงในรูปแบบ JSON

$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);

 

 

 

 

 

Rating

Average: 4 (5 votes)