商品の追加・削除 を行うウェブアプリを作成します。
フォーム上に追加ボタンと削除ボタンを用意して、
押されたボタンの名前により、処理を行います。
結果は商品一覧として表示します。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>SQL 条件を付けて検索</title> <link rel="stylesheet" href="../style.css"> </head> <body> <?php $db = new PDO("sqlite:test.db","",""); if( isset($_POST["insert"]) ){ //追加ボタン時の処理 $ipd = $_POST["insProduct"]; $ipc = $_POST["insPrice"]; $que ="INSERT INTO product(name,price) VALUES(:ipd,:ipc)"; $stmt = $db->prepare($que); $stmt->bindParam(":ipd" ,$ipd); $stmt->bindParam(":ipc" ,$ipc); $stmt->execute(); } elseif( isset($_POST["delete"]) ){ $did = $_POST["delID"]; $que = "DELETE FROM product WHERE id = :did"; $stmt = $db->prepare($que); $stmt->bindParam(":did", $did); $stmt->execute(); } $que = "SELECT * FROM product"; $data = $db->query($que); ?> <h1>在庫リスト</h1> <form action="" method="post"> 商品:<input type="text" name="insProduct"><br> 価格:<input type="text" name="insPrice"><br> <input type="submit" name="insert" value="追加"> <hr> <h1>商品一覧</h1> <table border="2"> <tr bgcolor="#b0b0b0"> <th>削除?</th> <th>番号</th> <th>商品</th> <th>単価</th> </tr> <?php while( $value = $data->fetch() ){ $id = $value["id"]; $name = $value["name"]; $price = $value["price"]; echo "<tr>" . "<td><input type=\"radio\" name=\"delID\" value=\"{$id}\"></td>" . "<td>{$id}</td>" . "<td>{$name}</td>" . "<td>{$price}</td>" . "</tr>"; } $db = null; ?> </table> <input type="submit" name="delete" value="削除" > </form> </body> </html> |