LoginSignup
9
21

More than 5 years have passed since last update.

【PHP】簡単!PDOを用いてデータベースを用いたサンプルアプリを作る【データベース】

Last updated at Posted at 2018-05-11

大まかな流れ

0.データベースを作成
1.フォーム画面のファイルを作る(zaiko_form.php)
2.1.のフォーム画面で入力したデータをデータベースに送信&「送信完了」的なメッセージを表示するファイルを作る(zaiko_send.php)
3.送信したデータを表示する画面を作る(zaiko_list.php)

0.データベースを作成

事前準備としてデータベースを準備しておく必要があります。私の環境では以下のように設定をしました。

今回のデータベース設定

  • 使用するデータベースシステム:MySQL
  • データベース名:akibadb
  • データベースのホスト:localhost
  • データベースユーザー名:root
  • データベースパスワード:root
  • テーブル名:zaiko

1.フォーム画面のファイルを作る(zaiko_form.php)

ここでは以下のような登録フォームを作成します。ここで入力したデータをデータベースに入れるのです。

 2018-05-12 2.08.08.png

zaiko_form.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>在庫フォーム</title>
    <style>
        body {
            width:60%;
            padding:20px 5%;
            margin:auto;
        }
        h1 {
            text-align:center;
        }
    </style>
</head>
<body>  
    <form action="zaiko_send.php" method="post">
        <table>
            <tr>
                <th>商品名</th>
                                <!-- nam -->
                <td><input type="text" name="item"></td>
            </tr>
            <tr>
                <th>商品説明</th>
                <td><textarea name="i_desc" id="" cols="30" rows="10"></textarea></td>
            </tr>
            <tr>
                <th>仕入先</th>
                <td><input type="text" name="i_comp"></td>
            </tr>
            <tr>
                <th>生産国</th>
                <td><input type="text" name="country"></td>
            </tr>
            <tr>
                <th>価格</th>
                <td><input type="text" name="price"></td>
            </tr>
            <tr>
                <th>仕入れ価格</th>
                <td><input type="text" name="w_price"></td>
            </tr>
            <tr>
                <th>在庫数</th>
                <td><input type="text" name="stock"></td>
            </tr>
            <tr>
                <th>入荷日</th>
                <td><input type="date" name="day"></td>
            </tr>
            <tr colspan="2">
                <td><input type="submit" value="送信"></td>
            </tr>
        </table>
    </form>
</body>
</html>

2.1.のフォーム画面で入力したデータをデータベースに送信&「送信完了」的なメッセージを表示するファイルを作る(zaiko_send.php)

実際に入力されたデータをデータベースにぶち込みます。データベースに無事入ったら以下のメッセージを表示します

 2018-05-12 2.08.14.png

zaiko_send.php

<!DOCTYPE html>
<html lang="jp">
<head>
    <meta charset="UTF-8">
    <title>在庫鮮度</title>
    <style>
        body {
            width:60%;
            padding:20px 5%;
            margin:auto;
        }
        h1 {
            text-align:center;
        }
    </style>
</head>
<body>
<?php
// 1.もし、ポストにデータがあるならば・・・
if (isset($_POST["item"], $_POST["i_desc"], $_POST["i_comp"], $_POST["country"], $_POST["price"], $_POST["w_price"], $_POST["stock"], $_POST["day"])) {
    // 2.ポストのデータを変数にしま~す
    $item = $_POST["item"];
    $i_desc = $_POST["i_desc"];
    $i_comp = $_POST["i_comp"];
    $country = $_POST["country"];
    $price = $_POST["price"];
    $w_price = $_POST["w_price"];
    $stock = $_POST["stock"];
    date_default_timezone_set('Asia/Tokyo');
    $day = date("Y-m-d");
}
// 3.データベースに接続しましょう
$pdo = new PDO(
    "mysql:dbname=akibadb;host=localhost","root","root",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET `utf8`")
);
// 4.データベースに繋がっているか確認します。
if ($pdo) {
    //繋がってるときはこんな表示したくないのでコメントアウト
    //echo "データベースに繋がっています";
} else {
    "データベースに繋がってないでござる";
}

// 5.在庫データベースのそれぞれのテーブルにデータをぶち込む準備をして、それを$regist変数に定義します~
$regist = $pdo->prepare("INSERT INTO zaiko(item, i_desc, i_comp, country, price, w_price, stock, day) VALUES (?,?,?,?,?,?,?,?)");

// ぶち込みのルールを決めます(?)
// データベースのそれぞれの引き出しに
//上で定義した変数の値をぶち込みます
//bindParamよくわかってないから後で調べます
$regist->bindParam("item", $item);
$regist->bindParam("i_desc", $i_desc);
$regist->bindParam("i_comp", $i_comp);
$regist->bindParam("country", $country);
$regist->bindParam("price", $price);
$regist->bindParam("w_price", $w_price);
$regist->bindParam("stock", $stock);
$regist->bindParam("day", $day);
// さぁ、ぶち込みを実行しましょう
$regist->execute(array($item, $i_desc, $i_comp, $country, $price, $w_price, $stock, $day));

if ($regist) {
    echo "登録完了したぜYay!";
} else {
    echo "エラーですクソコード書くな!";
}
?>
</body>
</html>

3.送信したデータを表示する画面を作る(zaiko_list.php)

実際にデータベースにぶち込んだデータを引っ張って表示させてみます。

 2018-05-12 2.09.12.png

zaiko_list.php

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>在庫リスト</title>
</head>
<body>
<?php

// 1.まずはデータベースに接続しましょう
$pdo = new PDO("mysql:dbname=akibadb;host=localhost;charset=utf8mb4",
    "root",
    "root");

// 2.データベースに繋がっているか確認しましょう
if ($pdo) {
    //繋がってるときはこんな表示したくないのでコメントアウト
    //echo "データベースに繋がっています";
} else {
    "データベースに繋がってないでござる";
}

// pdoデータベースのzaikoテーブルからカラムを選ぶ準備をして、$list変数のに定義します!
$list = $pdo->prepare("SELECT * FROM zaiko");
// 取り出し実行するぜ!!!!!!!!!!!
$list->execute();

if ($list) {
    echo "
        <table>
            <caption>
                <h2>商社データ</h2>
            </caption>
            <tr>
                <th>商品番号</th>
                <th>商品名</th>
                <th>商品説明</th>
                <th>仕入先</th>
                <th>生産国</th>
                <th>価格</th>
                <th>仕入れ価格</th>
                <th>在庫数</th>
                <th>入荷日</th>
            </tr>
    ";
    // $list->fetch()
    // データベースのデータはもともとカンマでつなげられているだけの長いCSVデータであり、配列ではない。
    // そこにfetch()することで、配列化をする。
    // while文は、TRUEである限りループをする。
    // while文がfalseになるときは、fetchできなくなったとき、すなわちすべてのデータを配列化し終えたとき。
    while ($data = $list->fetch()) {
        echo "
                <tr>
                    <th>{$data['id']}</th>
                    <th>{$data['item']}</th>
                    <th>{$data['i_desc']}</th>
                    <th>{$data['i_comp']}</th>
                    <th>{$data['country']}</th>
                    <th>{$data['price']}</th>
                    <th>{$data['w_price']}</th>
                    <th>{$data['stock']}</th>
                    <th>{$data['day']}</th>
                </tr>
        ";
    }
} else {
    echo "エラーです。お願いなのでクソコード書かないでください";
}

echo "</table>";

?>


</body>
</html>

以上です。

9
21
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
21