0

I'm creating a register for the user. If the user name already exists in the database the program needs to show a message. It works, but I don't know why the program does'nt show the message the first time. For example, if the name michael is already registered and I try to put again the message "user name already exists" is not displayed. But if I try again, then is displayed. Or if I try with another name already registered, is displayed. But not the first time, only the second and after. Could you help me please.

<?php
session_start();
if(!isset($_SESSION['$k'])) {
    $_SESSION['$k'] = false;
}
?>

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="register.css">
    <title>Word Games Register</title>
</head>

<body>
    <form action="" method="POST">
        <a href="../index.php"><img src="../img/close.png" /></a>
        <h2>REGISTRARSE</h2>
        <input type="text" placeholder="Usuario" name="user">
        <input type="password" placeholder="Contraseña" name="password">
        <input type="text" placeholder="E-mail" name="email">
        <?php
            if($_SESSION['$k']) {
                echo '<h5 id="mensaje">El usuario ya existe</h5>';
                unset($_SESSION['$k']);
            }
        ?>
        <input type="submit" value="Enviar" name="btn">
    </form>
</body>
</html>

<?php
if(isset($_POST['btn'])){
    $user = $_POST['user'];
    $pass = $_POST['password'];
    $email = $_POST['email'];

    $link = mysqli_connect("localhost", "root", "") or die ("Error       conectando al servidor" . mysqli_error());
    mysqli_select_db($link, "wordgames") or die ("Error seleccionando la base de datos" . mysqli_error());
    mysqli_query($link, "SET NAMES 'utf8'");

    $resultado = mysqli_query($link, "select * from usuario where usuario='$user'") or die ("Error en la consulta" . mysqli_error());
    $filas = mysqli_num_rows($resultado);
    if($filas > 0){
        $_SESSION['$k'] = true;
    } else{
        mysqli_query($link, "insert into usuario values (NULL, '$user', '$pass', '$email')") or die ("Error en la consulta". mysqli_error());
        mysqli_close($link);
        header("location:../index.php");
    }


}
?>
6
  • you need to run an ajax call to check the database and update the user live. Commented Apr 29, 2016 at 15:49
  • That would be fancy, but not strictly necessary. Commented Apr 29, 2016 at 16:03
  • Easy and common trouble. If you execute manualy your php in your mind, you'll see that, when you are in a POST context, you display the HTML first (so, no SESSION set), then parsing your $_POST to find there's already a user with your name and so, setting the SESSION to true. Then, nothing else, so your HTML is already built without your error message. The fact it appears when you refresh is just because it's stored in SESSION. Please, always do your PHP stuff BEFORE echoing any HTML text, and it will work. You also don't need SESSION to do that if you put your PHP part first. Commented Apr 29, 2016 at 16:25
  • Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Commented Apr 29, 2016 at 16:45
  • Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding. Commented Apr 29, 2016 at 16:45

1 Answer 1

2

You are checking if a certain session variable is set, and if so, you display your "User already exists" message. The point is that you set this variable after you have already printed everything, so basically you first check "Is it set?" and then you set it. As a result, your message is not printed (as that code is already evaluated).

As it is a session variable, it remains set during the session. Hence, if you reload the page, your message will show up. If you then try another existing user, the variable was already set previously, hence the message is shown (albeit basically for the previous username).

One way to fix this could be to move your lower PHP code block above your HTML; that way, your header("Location: ...") will also work.

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.