0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPで献立提案

Posted at

はじめに

PHPで献立を提案するプログラムを作りました。

フォームの作成

ジャンルテーブルは次のようになっています。

id name
1 和風
2 中華
3 洋風

valueにはそれに対応したPKが入っています。

<form method="post">
    <label>ジャンル</label>
    <input type="radio" name="genre" value="1"> 和風
    <input type="radio" name="genre" value="2"> 中華
    <input type="radio" name="genre" value="3"> 洋風

    <label>主菜</label>
    <input type="radio" name="food" value="1"><input type="radio" name="food" value="2"><input type="radio" name="food" value="3"><input type="radio" name="food" value="4"><label>調理法</label>
    <input type="radio" name="method" value="1"> 焼く
    <input type="radio" name="method" value="2"> 煮る
    <input type="radio" name="method" value="3"> 炒める
    <input type="radio" name="method" value="4"> 蒸す

    <button type="submit">献立を提案</button>
</form>

コントローラーの作成

POSTされると入力チェックをする。入力がないとエラーを返して、入力があるとモデルにデータを検索させる。

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($postData['genre']) || empty($postData['food']) || empty($postData['method'])) {
        $error = 'それぞれ選択してください';
    } else {
        $result = $this->menuModel->getSuggestedDish(
            $postData['genre'],
            $postData['food'],
            $postData['method']
        );
    }
}

モデルの作成

モデルは入力された値を使ってデータベースから値を取得する。

public function getSuggestedDish($genreId, $foodId, $methodId): string {
        $stmt = $this->pdo->prepare("
            SELECT dish_name
            FROM dishes
            WHERE genre_id = ? AND main_food_id = ? AND method_id = ?
            ORDER BY RAND()
            LIMIT 1
        ");
        $stmt->execute([$genreId, $foodId, $methodId]);

        $dish = $stmt->fetchColumn();
        return $dish ?: "該当する献立はありません";
    }

結果の表示

結果に値が入っている時だけHTMLを表示させます。

<?php if ($result): ?>
    <p>今日の献立: <strong><?php echo htmlspecialchars($result); ?></strong></p>
<?php endif; ?>

まとめ

フォームで入力された値から対応しているデータをデータベースから探してくる流れが分かりました。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?