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");
}
}
?>