0

This is my code

if ($row['username'] > 0) {
    array_push($errors, "Username already exist");
    die();
}

$passwordHash = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password, user_type) VALUES (:username, :password, :user_type)";
$stmt = $connect->prepare($sql);

$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
$stmt->bindValue(':user_type', 'user');
$result = $stmt->execute();

if ($result) {
    array_push($success, "Account Successfully Created!");
    header('Location: /');
    exit;
}

How do I echo the array_push($errors... to the same page because it happens that after the form sent it is showing me white page but the same URL. Also, in array_push($success... I want it to echo the message in the other page.

Michael
  • 3,093
  • 7
  • 39
  • 83
  • If I am following you perhaps do some Googling on "**Flash messages**" and "**Sessions**". FWIW: [Cookie vs. Session based flash message](https://stackoverflow.com/questions/6021520/cookie-vs-session-based-flash-message) – ficuscr Aug 20 '19 at 16:29
  • Use session to persist the message on page request but make sure it's only available until the next request. Also agree with @ficuscr, "Flash messages" is what you're looking for. – xDiff Aug 20 '19 at 16:37

2 Answers2

1

It's not clear question for me, But if you mean that you want to pass something to another page!

So you can use SESSION like this way.

FirstPage.php

<?php

// Start the session before using it.
session_start();

if($row['username'] > 0) {
    array_push($errors, "Username already exist");

    // Create new session variable,
    //      Or reset the value of it if it's already exists.
    $_SESSION['error'] = "Username already exist";

    // Go to the "SecondPage.php"
    header('Location: SecondPage.php');

    die();
}

?>

SecondPage.php

<?php

// Start the session before using it.
session_start();

// Checking if there is a Session called "error".
if(isset($_SESSION['error']) && $_SESSION['error'] != "") {
    // So, there is an session with "error" variable saved on the Client's website.

    // Echo the saved "error" variable from the session.
    echo $_SESSION['error'];

    // Reset / Remove the error so it won't be visible next time we visit this page.
    $_SESSION['error'] = "";
}

?>
0

As the array_push() will push the element to the end of the array, you can use the end() function:

echo end($errors);

Use the name of the array inside of the end function which you want to access. Example: https://paiza.io/projects/zIhh0wUf17hEdY1juVK26A