0

This is a simplified version of a project I'm working on.

The main idea is that test.php sends 'acct-id' to submitData.php and it validates if the account ID already exists in the server. In case it already exists, I want to send an error message to test.php.

I have built this code but I can't get '$err_msg' to change it's value in test.php. This variable changes it's value within the 'while' loop but it does not change outside it.

How can I send $err_msg value to test.php?

Thanks in advance to all possible help.

test.php

<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="submitData.php" method="POST">
        <input type="text" name="acct-id">
        <input type="submit" name="submit-btn">
        <?=$err_msg?>
    </form>
</body>
</html>

submitData.php

<?php
include '../tools/db_config.php';
$err_msg = "test";

if(isset($_POST["submit-btn"])){
    $acct_id = $_POST["acct-id"];

    $sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
    if ( $result = $conn->query($sql) ){
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $err_msg = "This account already exists.";
            }
            header('Location: test.php');
        }
    }else {
            $output="Error en la consulta: ".$conn->error;
    }
}

?>

1 Answer 1

1

You can use Session for this.

<?php
include '../tools/db_config.php';
session_start();
$err_msg = "test";
if(isset($_POST["submit-btn"])){
    $acct_id = $_POST["acct-id"];
    $sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
    if ( $result = $conn->query($sql) ){
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $err_msg = "This account already exists.";
            }
            $_SESSION['err_msg']     = $err_msg;
            header('Location: test.php');
        }
    }else {

            $output="Error en la consulta: ".$conn->error;
    }
}

?
<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="submitData.php" method="POST">
        <input type="text" name="acct-id">
        <input type="submit" name="submit-btn">
        <?=$_SESSION['err_msg']?>
    </form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.