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(':name' => 笨兔, ':sort' => 測試, ':id' => 1);
$sql = "UPDATE game SET a_name = :name, a_sort = :sort WHERE a_id = :id";
$rs = $conn -> prepare($sql);
$rs -> execute($input);//寫法之2
$sql = "UPDATE game SET a_name = ?, a_sort = ? WHERE a_id = ? ";
$rs = $conn -> prepare($sql);
$rs -> execute(array(笨兔, 測試, 1));//寫法之3?>
$name = '笨兔';
$sort = '測試'; $id = '1';
$sql = "UPDATE game SET a_name = '$name', a_sort = '$sort' WHERE a_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 表單變數條件,撈取要修改的筆數以秀在網頁修改欄內 $sql = "SELECT * FROM learn_demo WHERE t_id=".$_GET['t_id']; $rs = $conn -> prepare($sql);
$rs -> execute(); //判斷表單是否按送出而執行修改 if((isset($_POST['t_modify'])) && ($_POST['t_modify']=='yes')){ $id=$_POST['t_id']; $name=addslashes($_POST['t_name']); $note=$_POST['t_note']; $sql="UPDATE learn_demo SET t_name='$name', t_note='$note' WHERE t_id='$id'"; $rs = $conn -> prepare($sql);
$rs -> execute();
header("Location: db_008_1.html"); //修改後前往某網頁 } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>喵喵笨兔 - PHP 網頁編輯 MySQL 資料庫:修改資料</title> </head> <body> <div> <?php while($row = $rs -> fetch(PDO::FETCH_ASSOC)){ ?> <form method="post" name="form"> <table align="center"> <tr> <td>名稱:</td> <td><input type="text" name="t_name" value="<?php echo htmlentities($row['t_name']); ?>" required></td> </tr> <tr> <td>備註:</td> <td><input type="text" name="t_note" value="<?php echo $row['t_note']; ?>"></td> </tr> <tr> <td> </td> <td><input type="reset" value="重設"><input type="submit" value="確定"></td> </tr> </table> <input name="t_modify" type="hidden" value="yes"><? //隱藏欄位用來判斷是否送出,來做修改的動作 ?> <input name="t_id" type="hidden" value="<?php echo $_GET['t_id']; //記錄篩選條件 ?>"> </form> <?php } ?> </div> </body> </html>
※PHP Data Objects (PDO) 與 MySQL 資料庫相關應用,可參考笨兔其它隨手筆記:
※PHP 其它函數 MySQL 和 MySQLi 連接資料庫相關應用,可參考笨兔の隨手筆記: