テーブル1:orders
カラム:id(int not null primary 4), name(varchar 20), older(int 4)
今回は上記のテーブルのレコードを例に削除しています。
PHP上でMySQLのテーブルのレコードを削除するためのソースコード
test.php
<?php $dsn = 'mysql:host=localhost;dbname=my_db;charset=utf8;'; $row = ['name' =>' ', 'password' => 0]; $id = false; if(isset($_GET['id'])){ $id = $_GET['id']; } if($_SERVER["REQUEST_METHOD"]=='POST'){ try{ $pdo = new PDO($dsn, 'root', ' '); #SQL文(DELETE) $sql = 'delete from orders where id = :id'; #prepareの実行 $stmt = $pdo -> prepare($sql); #idの値をバインド $stmt -> bindValue(':id', $id, PDO::PARAM_INT); #DELETEした結果を実行 $stmt -> execute(); #リダイレクト header('Location: .'); exit; }catch(PDOException $e){ $message = $e -> getMessage(); }else{ if(id != false){ try{ $pdo = new PDO($dsn, 'root', ' '); $sql = 'select * from orders where id = ' . $id'; $stmt = $pdo -> query($sql); $row = $stmt -> fetch(); $message = 'orders id は' . $id; }catch(PDOException $e){ $message = $e->getMessage(); } } } try{ $pdo = new PDO($dsn, 'root', ' '); $sql = 'select * from orders where id = ' . $id'; $stmt = $pdo -> query($sql); }catch(PDOException $e){ $message = $e -> getMessage(); } ?> <?php if($id != false) { ?> <form method="post" action=". /?id=<?=$id ?>"> <table> <tr> <th>氏名</th> <td><?=$row['name'] ?></td> </tr> <tr> <th>年齢</th> <td><?=$row['older'] ?></td> </tr> <tr> <th>情報を送信する</th> <td><input type="submit"></td> </tr> </table> </form> <?php } ?>