PHP PDO(Php Data Object)是一個強大的數據庫擴展,可以在PHP中操作大多數數據庫,例如MySQL,MSSQL和Oracle等等。本文將為您詳細介紹PHP PDO的使用方法,包括如何連接到數據庫、執行SQL查詢、插入、更新和刪除數據等。
連接到數據庫
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
執行SQL查詢
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
插入數據
$stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :password)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
if($stmt->execute()){
echo "New record created successfully";
} else{
echo "Unable to create record";
}
更新數據
$stmt = $conn->prepare("UPDATE users SET name=:name,email=:email,password=:password WHERE id=:id");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':id', $id);
if($stmt->execute()){
echo "Record updated successfully";
} else{
echo "Unable to update record";
}
刪除數據
$stmt = $conn->prepare("DELETE FROM users WHERE id=:id");
$stmt->bindParam(':id', $id);
if($stmt->execute()){
echo "Record deleted successfully";
} else{
echo "Unable to delete record";
}
以上就是PHP PDO的基本用法,它可以輕松的操作數據庫,而且比其它的數據庫擴展更為簡單,如果您正在使用PHP開發Web應用,那么PHP PDO是個不錯的選擇。