Home > database >  Looping through multiple error messages inside the session, PHP
Looping through multiple error messages inside the session, PHP

Time:01-30

I am aware that making a specific session for each individual message, and then checking if the session isset, echo and unset works for displaying and removing on refresh.

What i'm trying to achieve is assigning several different messages to one $_SESSION['message']. On the next page (account.php), loop through the messages and display the correct message. How do I go about doing that?

The code I currently have:

    // Make sure the post values aren't empty.
    if (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['mail_address']) && !empty($_POST['password']) && !empty($_POST['confirm_password'])) {
        // When post values are filled, check if the password is equal to the password confirmation.
        if (($_POST['password']) == ($_POST['confirm_password'])) {
            // When the password and confirmation match, assign the post values to a variable.
            $first = $_POST['first_name'];
            $last = $_POST['last_name'];
            $mail = $_POST['mail_address'];
            $pass = $_POST['password']; 
            $hash = hash('sha256', $pass); // Password will be hashed.

            // Prevent duplicates by checking if the user already exists.
            $fetchExistingAccount = 'SELECT * FROM account WHERE sMailAddress = :post_mail';
            $stmt = $pdo->prepare($fetchExistingAccount);
            $stmt->execute([
                ':post_mail' => $mail
            ]);
            
            // Assigning rowCount result to a readable variable.
            $existingAccount = $stmt->rowCount();

            if ($existingAccount > 0) { 
                // If more than zero results are found,
                
                $_SESSION['message'] = 'E-mail already exists.';
                header('location: template/account.php?register');
            } elseif ($existingAccount == 0) {
                // When no results are found, insert post values into database.
                $insertAccount = 'INSERT INTO account (sFirstname, sLastname, sMailaddress, sPassword)
                VALUES (:post_first, :post_last, :post_mail, :post_pass)';
                $stmt = $pdo->prepare($insertAccount);
                $stmt->execute([
                    ':post_first' => $first,
                    ':post_last' => $last,
                    ':post_mail' => $mail,
                    ':post_pass' => $hash
                ]);
                $_SESSION['message'] = 'Successfully created new account.';
                header('location: template/account.php?');
            }
        } else {
            $_SESSION['message'] = 'Password does not match confirmation.';
            header('location: template/account.php?register');
        }
    } else {
        $_SESSION['message'] = 'All fields are required.';
        header('location: template/account.php?register');
    }
}

CodePudding user response:

In your code you are overwriting the value stored in $_SESSION['message'] with newer value so only the latest one will remain in the $_SESSION['message'].

To be able to assign multiple values into single variable you have to work with the variable as with the array(). And assign any new value/message into new empty key using $_SESSION['message'][] = 'new message'; using those empty brackets [];

On the script reading and printing the messages you will simply loop through the $_SESSION['message'] array, read each message one by one, print it and unset it from the array.

There are multiple ways how to achieve this for example this way using while() and array_pop()

<?php

$_SESSION['messages'] =  array("orange", "banana", "apple", "raspberry");

while (count($_SESSION['messages']) > 0){
    echo array_pop($_SESSION['messages']) . PHP_EOL;
}

Live demo

CodePudding user response:

I've modified your code and added some basic validation. Try this code

// check if a post request is made to the server
if( $_SERVER['REQUEST_METHOD'] === 'POST' ){
    $errors = [];

    // validate fields
    if( empty($_POST['first_name']) ){ // ensure the first_name is not empty
        $errors['first_name'] = 'First name is required.';
    }

    if( empty($_POST['last_name']) ){ // ensure the last_name is not empty
        $errors['last_name'] = 'Last name is required.';
    }

    if( empty($_POST['mail_address']) ){ // ensure the mail_address is not empty
        $errors['mail_address'] = 'Email address is required.';
    }else if( filter_var($_POST['mail_address'], FILTER_VALIDATE_EMAIL) ){ // ensure the mail_address is a valid email
        $errors['mail_address'] = 'A valid email address is required.';
    }else{
        // prevent duplicates by checking if the user already exist.
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM account WHERE sMailAddress = :sMailAddress");
        $stmt->execute(['sMailAddress' => $_POST['mail_address']]);

        if( $stmt->fetch()[0] > 0 ){ // if user exist add error
            $errors['mail_address'] = 'E-mail already exists.';
        }
    }

    if( empty($_POST['password']) ){ // ensure the password is not empty
        $errors['password'] = 'Password is required.';
    }

    if( empty($_POST['confirm_password']) ){ // ensure the confirm_password is not empty
        $errors['confirm_password'] = 'Confirm password is required.';
    }else if( $_POST['password'] === $_POST['confirm_password'] ){ // ensure the passwords match
        $errors['confirm_password'] = 'Password does not match.';
    }

    if( count($errors) === 0 ){ // if there are no errors, insert into database
        $first = $_POST['first_name'];
        $last  = $_POST['last_name'];
        $mail  = $_POST['mail_address'];
        $pass  = $_POST['password']; 
        $hash  = hash('sha256', $_POST['password']); // Password will be hashed.

        $stmt = $pdo->prepare("
            INSERT INTO account (sFirstname, sLastname, sMailaddress, sPassword)
            VALUES (:sFirstname, :sLastname, :sMailaddress, :sPassword)
        ");
        $stmt->execute([
            'sFirstname'   => $first,
            'sLastname'    => $last,
            'sMailaddress' => $mail,
            'sPassword'    => $hash
        ]);
        $_SESSION['success'] = 'Successfully created new account.';
        header('location: template/account.php');
    }else{ // if there are errors, put the errors into session
        $_SESSION['message'] = $errors;
        header('location: template/account.php?register');
    }
}

So, if the form fails, you'll have all the errors as an array in $_SESSION['message']. You can iterate over it, pull individual errors, etc. Also, when it passes, you will get a success message in $_SESSION['success'] to work with.

  •  Tags:  
  • Related