pdo echo error message when invalid username or pa

2020-05-06 07:53发布

问题:

hello i am relatively new to pdo(php) and i created a basic login system i know it is not secure yet but i am just experimenting anyway i know in the old php you could echo out and error message within an if statement but it does not seem to work anymore here is my script is it that im doing something wrong or that you just cant do that in pdo anymore.

if ($row == null){

            header( "location: login.html");
            echo "login failed";

        } else{

            header("location: homepage.php");
        }

i realize that this may not have enough code available so here is the rest of the script

session_start();
    //connection String
    $connection = new PDO("sqlsrv:server=server;Database=database", "username", "password"); 

    //Seelcting function
    $smt = $connection->prepare("select user_id, username from account where username = :username and password =:password");

    //setting values to textboxes
    $username = $_POST["txt_username"];
    $password = $_POST["txt_password"];

    //binding values
    $smt->bindValue(':username', $username);
    $smt->bindValue(':password', $password);

    //execution
    $smt->execute();

    //fetching data
    $row = $smt->fetch( PDO::FETCH_ASSOC ) ;  
    echo "$row[user_id]\n\n";
    echo "$row[username]\n\n";
    $_SESSION{"user_id"} = $row["user_id"];

回答1:

After you send the

header( "location: login.html");

the browser will redirect to that new file (login.html) and ignore (almost) any further output.

Do display the message on login.html later on, you have to use some mechanism to transfer the message to that page, e.g., by using a session variable.

EDIT

The header command send some kind of data to the browser before the actual content. If you make the browser redirect using a header, the user never gets to see the content.

So you need some way of bringing the content to the next page, you are redirecting to.

One possibility would be to use a session variable.

if ($row == null){
  $_SESSION['errormsg'] = "login failed";
  header( "location: login.php");
} else{
  header("location: homepage.php");
}

In the login.php then you could react to this message if it is present:

if( isset( $_SESSION['errormsg'] ) ) {
  // do the output
  echo $_SESSION['errormsg'];
  // delete the message from the session, so that we show it only once
  unset( $_SESSION['errormsg'] );
}


标签: php html pdo