0
0

More than 1 year has passed since last update.

user登録者毎に画面表示させる方法

Last updated at Posted at 2022-10-19

「id」を使って、各ユーザー毎に画面表示させる方法を学習したので、皆さんに共有します。

当初の遷移方法は
reg.php(登録画面) → reg_list.php(登録一覧画面) となる。

reg.php(入力画面)


               <div class="form_title">
          <div class="date">日付:<?php echo date("m月d日");?></div>
          <div class="input_form">
            <form method="post" action="reg_list.php" class="reg_method">
              <input type="text" name="title" class="reg_input">
              <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']?>">
              <input type="hidden" name="created_at">
              <button class="hozon">保存</button>
            </form>
          </div>
        </div>

inputタグの name="title" で入力を行う。

reg_list.php 1/2 インサート画面


<?php
   try {
      $pdo->beginTransaction();
      // データをSQLに登録する
      $stmt = $pdo->prepare('INSERT INTO tasks (title,user_id) VALUES (:title, :user_id)');

      // バインドパラムでセットする
      $stmt->bindParam( ':title', $title, PDO::PARAM_STR);
      $stmt->bindParam( ':user_id',$_SESSION["id"], PDO::PARAM_INT);
 
      // SQL実行
      $res = $stmt->execute();

      // コミット
      if( $res ) {
        $pdo->commit();
      }
      //ここでトランザクション終了。
    } catch(PDOException $e) {

      // ロールバック
      $pdo->rollBack();

      // エラーメッセージを出力
      echo $e->getMessage();
      exit;
    }
    header("Location:./reg_list.php");
    exit();
  };

データをSQLに登録する。「user_id」を登録することによって、
データベースの「title」の列表示がnull → ID番号へになる。

バインドパラムの「 $_SESSION["id"] 」をSESSIONからidを引っ張ってくることによって
別のテーブル(users)とtasksのIDをリンクさせる準備をする。

$res = $stmt->execute(); を実施してSQL実行する。

※$_SESSION["id"]はスーパーグローバル変数になるため必ず大文字で 「 SESSION   」と記述する

reg_list.php 2/2 画面表示画面

  //画面表示start。
  try {
    // データを取得するSQL
    $stmt = $pdo->prepare("SELECT id, title, done_at, user_id FROM tasks where user_id=:user_id");
    $stmt->bindParam( ':user_id', $_SESSION["id"], PDO::PARAM_INT);


    // SQL実行
    $res = $stmt->execute();

    $titless = $stmt->fetchAll(PDO::FETCH_ASSOC);  //title全てを抽出し、$titlessに入れる

  } catch(PDOException $e) {
    // エラーメッセージを出力
    echo $e->getMessage();
  } finally {

    // データベースの接続解除
    $pdo = null;
  }

?>

画面表示を行う。
("select id, title, done_at, user_id FROM tasks where user_id=:user_id");
$stmt->bindParam( ':user_id', $_SESSION["id"], PDO::PARAM_INT);
taskの中の「user_id」をバインドパラムにセットする。
$_SESSION["id"]はusersテーブルから取得する。

※$_SESSION["id"]はスーパーグローバル変数になるため必ず大文字で 「 SESSION   」と記述する

$res = $stmt->execute();
SQLを実行する。

まとめ
sessionを使えば、今までformでやっていた削除や編集もidで取得してできそうなので、次回挑戦してみたい

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