PHP Data Objects (PDO) 編緝 MySQL 資料庫:刪除資料
php 用 PDO 刪除 MySQL 資料庫
MySQL 設定的相關名稱,及範例寫法如下:
範例程式碼:
<?php try{
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$conn = new PDO($dsn, 'root', '1234');
//發生錯誤出現錯誤提醒
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
//發生錯誤結束資料庫連線並顯示錯誤訊息
die($e -> getMessage());
}
$input = array(':id' => 1);
$sql = "DELETE FROM game WHERE a_id = :id";
$rs = $conn -> prepare($sql);
$rs -> execute($input);//寫法之2
$sql = "DELETE FROM game WHERE id = ?";
$rs = $conn -> prepare($sql);
$rs -> execute(array(1));//寫法之3?>
$id = '1'; $sql = "DELETE FROM game WHERE id = {$id}"; //$sql = "DELETE FROM game WHERE id =".$id; //此行寫法同上行
//$rs = $conn -> exec($sql); //此行=下列二行
$rs = $conn -> prepare($sql);
$rs -> execute();
紅色字部份
。^ ^
<?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = '12345678'; $dbname = 'pcgame'; try{
$dsn = "mysql:host={$dbhost};dbname={$dbname};charset=utf8";
$conn = new PDO($dsn, $dbuser, $dbpass);
//發生錯誤出現錯誤提醒
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e){
//發生錯誤結束資料庫連線並顯示錯誤訊息
die($e -> getMessage());
} //依表單變數 $_GET['t_id'] 傳來的條件值進行刪除動作 $sql = "DELETE FROM learn_demo WHERE t_id=".$_GET['t_id']; $rs = $conn -> prepare($sql);
$rs -> execute(); //刪除後直接返回某網頁 header('location: db_008_1.html'); ?>
※PHP Data Objects (PDO) 與 MySQL 資料庫相關應用,可參考笨兔其它隨手筆記:
※PHP 其它函數 MySQL 和 MySQLi 連接資料庫相關應用,可參考笨兔の隨手筆記: