0
0

More than 1 year has passed since last update.

php バリデーションエラーを画面表示方法

Posted at

PHPのバリデーションについて学習したので皆さんに紹介します。

プログラミング初級者ですが、学んでいる身としては、バリデーションはPHPを作成する上で
とても重要なスキルで、PHPをして行く中で重要なので、

user_reg.php(新規登録画面)


<form method="post" action="user_back_reg.php">         
      <div class="container">
        <div class="form_title">
          <div class="date">名前: </div>
          <input type="text" name="name" class="reg_input">
        </div>
        <div class="form_title">
          <div class="date">年齢: </div>
          <input type="text" name="age" class="reg_input">
        </div>
        <div class="form_title">
          <div class="date">mail: </div>
          <input type="text" name="mail" class="reg_input">
        </div>
        <div class="form_title">
          <div class="date">ID:  </div>
          <input type="text" name="login_id" class="reg_input">
        </div>
        <div class="form_title">
          <div class="date">PW: </div>
          <input type="text" name="login_pw" class="reg_input">
        </div>
        <div>
          <button class="user_reg">保存</button>
        </div>
      </div>
    </form>

※formを使って、「name」「age」「mail」「login_id」「login_pw」をuser_back_reg.phpへPOST送信する

user_back_reg.php(処理画面)


// ポストデータを取得する。変数に値が入っているかどうかを確認するためのisset関数
  if(isset($_POST["name"]) || isset($_POST["age"]) || isset($_POST["mail"]) || isset($_POST["login_id"])
                           || isset($_POST["login_pw"])){

    $name      = $_POST["name"];
    $age       = $_POST["age"];
    $mail      = $_POST["mail"]; 
    $login_id  = $_POST["login_id"];
    $login_pw_nomal  = $_POST["login_pw"]; 


    $errors = [];
      
    // $name、セットされているか、空文字でないか、10文字以下(11文字はだめ)であるか、文字列型であるか 
    if(!$name || $name === "") {  
      $errors["name_required"] = "名前は必須です";
    }

    if(gettype($name) !== "string") {
      $errors["name_data_type"] = "名前は文字列型で入力してください。";
    }
    
    if(mb_strlen($name, 'utf8') >= 10) {
      $errors["name_max_counts"] = "名前は10文字以内で入力してください。"; 
    }


    // $age、セットされているか、空文字でないか、数値型であるか(整数型)、150歳以下であるか、
    if(!$age || $age === "") {  
      $errors["age_required"] = "年齢は必須です";
    }

    if(!preg_match("/^[0-9]+$/",$age)) { 
      $errors["age_data_type"] = "年齢は数値型で入力してください。";
    }

    if($age >= 150 ){
      $errors["age_max_counts"] = "150歳以下で入力お願いします。";
    }

    // mail セットされているか、空文字でないか、10文字以下(11文字はだめ)であるか、文字列型であるか
    if(!$mail || $mail === "") {
      $errors["mail_required"] = "mailは必須です";
    }

    if(gettype($mail) !== "string") {
      $errors["mail_data_type"] = "メールアドレスを入力してください";
    }
    
    if(mb_strlen($mail, 'utf8') >= 20) { 
      $errors["mail_max_counts"] = "nameは20文字以内で入力してください。";
    }
      
    // login_id セットされているか、空文字でないか、10文字以下(11文字はだめ)であるか、文字列型である、半角英数であるか
    if(!$login_id || $login_id === "") {
      $errors["login_id_required"] = "IDは必須です";
    }

    if(gettype($login_id) !== "string") {
      $errors["login_id_data_type"] = "IDは数値で入力してください。";
    }

    if(mb_strlen($login_id, 'utf8') >= 10) {  
      $errors["login_id_max_counts"] = "IDは10文字以内で入力してください。";
    }

    if(!preg_match("/^[0-9]+$/",$age)) {
      $errors["login_id_required"] = "数字を入れてください";
    }

    // login_pw_nomal セットされているか、空文字でないか、10文字以下(11文字はだめ)であるか、文字列型である、半角英数であるか
    if(!$login_pw_nomal || $login_pw_nomal === "") {
      $errors["login_pw_nomal_required"] = "パスワードは必須です";
    }

    if(mb_strlen($login_pw_nomal, 'utf8') >= 10) {
      $errors["login_pw_nomal_max_counts"] = "パスワードは10文字以内で入力してください。"; 
    }

    if(!preg_match("/^[0-9]+$/",$age)) {
      $errors["login_id_required"] = "数字を入れてください";
    }

    // $errors[]; エラーがあれば、エラーを配列に入れる $errorsが空配列であれば、バリデーションを突破、データベース保存へ
    if(count($errors) > 0){
      $_SESSION["errors"] = $errors;
      header("Location:./user_reg.php");
      exit();
    }

    $login_pw_hash = hh($login_pw_nomal);

    try {
      // トランザクション開始(ロック)
      $pdo->beginTransaction();

      // データを登録するSQL
      $stmt = $pdo->prepare('INSERT INTO users(name, age, mail, login_id,login_pw)VALUES(:name, :age, :mail, :login_id, :login_pw)');
      
      // バインドパラムでセットする
      $stmt->bindParam( ':name',     $name,     PDO::PARAM_STR);
      $stmt->bindParam( ':age',      $age,      PDO::PARAM_INT);
      $stmt->bindParam( ':mail',     $mail,     PDO::PARAM_STR);
      $stmt->bindParam( ':login_id', $login_id, PDO::PARAM_STR);
      $stmt->bindParam( ':login_pw', $login_pw_hash, PDO::PARAM_STR);

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

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

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

      // エラーメッセージを出力
      echo $e->getMessage();
      exit;
    }
    header("Location:./user_list.php");  
    exit();
  } else {
    $_SESSION["errors"]["no_post"] = "必要情報を入力してください";
    header("Location:./user_reg.php");
  }
※$errors[];に入っている$errorsが1個以上あるならば、$_SESSION["errors"]へ格納後、
 「user_reg.php"」へ移動。
if(count($errors) > 0){
  $_SESSION["errors"] = $errors;
  header("Location:./user_reg.php");
  exit();
}

user_reg.php(新規登録にエラー出力画面)


    //もし、エラーある。または、エラーが0以上ある場合は  sesionエラーを$errorsへ
    $errors = [];
    if(isset($_SESSION["errors"]) && count($_SESSION["errors"]) > 0){
      $errors = $_SESSION["errors"];
      $_SESSION["errors"] = [];
    } 





    <div class="container">
      <?php if (count($errors) > 0) : ?>
          <?php foreach ($errors as $key => $error) : ?>
              <div class="errors"><?= $error ?></div>
          <?php endforeach; ?>
      <?php endif; ?>
    </div>

※1個以上エラーがある場合は、$errorをすべて出力(foreach文)する

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