Config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pdoexample";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->exec("set names utf8");
}catch(PDOException $e){
echo $e->getMessage();
}
?>
INSERT
<?php require_once("config.php");
$str_name = "ทดสอบชื่อ1";
$str_username = "username1";
$str_password = md5("password1");
$stmt = $conn->prepare("INSERT INTO users (u_name, u_username, u_password) VALUES (?, ?, ?)");
$stmt->bindParam(1, $str_name);
$stmt->bindParam(2, $str_username);
$stmt->bindParam(3, $str_password);
if($stmt->execute()){
$last_id = $conn->lastInsertId();
echo "insert success last id : ".$last_id;
}else{
echo "insert fail !";
}
?>
UPDATE
<?php require_once("config.php");
if(isset($_GET["id"])){
$id = (int)$_GET["id"];
$name = "testname2";
$username = "testusername2";
$password = "testpassword2";
$stmt = $conn->prepare("UPDATE users SET u_name = ?, u_username = ?, u_password = ? WHERE u_id = ?");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $username);
$stmt->bindParam(3, $password);
$stmt->bindParam(4, $id);
$result = $stmt->execute();
if($result == true){
echo "update success";
}else{
echo "update fail !";
}
}else{
echo "โปรดระบุไอดี";
}
?>
SELECT
<?php require_once("config.php");
if(isset($_GET["id"])){
$id = (int)$_GET["id"];
$stmt = $conn->prepare('SELECT u_id, u_name, u_username, u_password FROM users WHERE u_id = ?');
$stmt->bindParam(1, $id);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $r){
echo $r["u_id"]."<br>";
echo $r["u_name"]."<br>";
echo $r["u_username"]."<br>";
echo $r["u_password"]."<br>";
}
-
}else{
echo "โปรดระบุ id";
}
?>
DELETE
<?php require_once("config.php");
if(isset($_GET["id"])){
$id = (int)$_GET["id"];
$stmt = $conn->prepare("DELETE FROM users WHERE u_id= ?");
$stmt->bindParam(1, $id);
$result = $stmt->execute();
if($result == true){
echo "delete success";
}else{
echo "delete fail !";
}
}else{
echo "โปรดระบุไอดี";
}
?>