【超初心者向け】お店レビューアプリのUpdate機能を作成しよう

あけお

スクールに多額のお金を支払う前に、僕の記事で学習してみてね!!

こんな人に読んでほしい
  1. 基礎は学んだけど、アプリ作成って何をすればいいの?
  2. そもそも何を勉強すればいいの?
  3. ポートフォリオ作らなきゃヤバい、、
https://akeoblog.com/phptutorial/
目次

この記事でやること

  • Update機能を作成する体験をする
  • お店レビューの編集機能を追加する

1. 準備をしよう

ここでは、「簡易的なTwitterアプリ」を参考に機能を追加します。

まだ、「簡易的なTwitterアプリ」を学習していない方は、先に学びましょう。
以下の記事で学べます!!!

https://akeoblog.com/phpsimpletwitterapp/

1. GitHubを開きます。

以下のURLからサイトを開きます。
https://github.com/Aka023v/restaurant-review-update

2. 「Codespaces」を使い、環境構築をします。

※ 環境構築方法がわからない方は、以下URLの記事を参考にしましょう!

https://akeoblog.com/gitgithubcodespaces/

2. 編集機能を作成しよう

1. edit.phpに編集ページを作成しよう

※ 以下の「簡易的なTwitterアプリ」の「edit.php」を参考にしよう。
https://github.com/Aka023v/simple-twitter

2. update.phpに編集機能を作成しよう

※ 以下の「簡易的なTwitterアプリ」の「update.php」を参考にしよう。
https://github.com/Aka023v/simple-twitter

3. 回答を確認しよう

回答を確認しましょう!
できなかった方は、以下のコードを真似して修正してみましょう。

edit.php

<?php
$id = filter_input(INPUT_GET, 'id');

$dbh = new PDO(
  'mysql:dbname=restaurant_review;host=mysql;charset=utf8',
  'root',
  'password'
);
$query = "SELECT * FROM review where id = '$id'";
$stmt = $dbh->query($query);
$review = $stmt->fetch();
?>

<body>
  <div>
    <h1>編集</h1>
    <form method="post" action="./update.php">
      <input type="hidden" name="id" value=<?php echo $review['id'] ?>>
      <div>
        <label for="poster">投稿者名
          <input type="text" name="poster" value=<?php echo $review['poster'] ?>>
        </label>
      </div>
      <div>
        <label for="restaurant_name">レストラン名
          <input type="text" name="restaurant_name" value=<?php echo $review['restaurant_name'] ?>>
        </label>
      </div>
      <div>
        <label for="review">レビュー
          <input type="textarea" name="review" value=<?php echo $review['review'] ?>>
        </label>
      </div>
      <button>更新</button>
    </form>
  </div>
</body>

update.php

<?php
$id = filter_input(INPUT_POST, 'id');
$poster = filter_input(INPUT_POST, 'poster');
$restaurant_name = filter_input(INPUT_POST, 'restaurant_name');
$review = filter_input(INPUT_POST, 'review');

$dbh = new PDO(
  'mysql:dbname=restaurant_review;host=mysql;charset=utf8',
  'root',
  'password'
);
$query = "UPDATE review SET poster='$poster', restaurant_name='$restaurant_name', review='$review' WHERE id = '$id'";
$dbh->query($query);

header('Location: ./index.php');
exit;
?>
よかったらシェアしてね!
目次