Validate the record in bdd

0

I have a problem when registering a user. When I register a user for the second time, the error message "Registered user" is displayed but the same is added to the bdd. What can I do to prevent this from happening?

Thank you.

Php code

<?php 

    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];
    $usuario = $_POST['usuario'];
    $pass = $_POST['pass'];
    $correo = $_POST['correo'];
    $perfil = $_POST['perfil'];

    $conexion = mysqli_connect("localhost","root","","formbd");

    $insertar = "INSERT INTO usuarios (nombre,apellido,usuario,pass,correo,perfil)VALUES('$nombre','$apellido','$usuario','$pass','$correo','$perfil')";

    $sql = "SELECT * FROM usuarios WHERE usuario = '$usuario'";
    $sql2 = "SELECT * FROM usuarios WHERE correo = '$correo'";

    $result = $conexion -> query($sql);
    $result2 = $conexion -> query($sql2);
    $resultado = mysqli_query($conexion,$insertar);

    if(!$resultado)
    {
        echo "<h4 align=center><font color=\"#FF0000\">Error al registrarse </font></h4>";
        $resultado = false;
    }
    elseif($result -> num_rows > 0)
    {
        echo "<h4 align=center><font color=\"#FF0000\">Error al registrarse </font></h4>";
        echo "<h5 align=center><font color=\"#FF0000\">El usuario ya existe</font></h5>";
        $resultado = false;

    }
    elseif($result2 -> num_rows > 0)
    {
        echo "<h4 align=center><font color=\"#FF0000\">Error al registrarse </font></h4>";
        echo "<h5 align=center><font color=\"#FF0000\">El correo ya existe</font></h5>";
        $resultado = false;
    }
    else
    {
        echo "<h4 align=center><font color=\"#008000\">Registrado correctamente</font></h4>";
        $resultado = true;
    }



    mysqli_close($conexion);

? >

    
asked by Cristobal 20.06.2018 в 19:28
source

1 answer

0

Instead of doing that, simplify the querys in the following way:

SELECT usuario,correo FROM usuarios WHERE usuario = '$usuario' AND correo = '$correo';

I would use prepared statements to avoid sql injection problems, but if you still prefer to do it this way, first execute that query, then check if the columns exist or not with a if , and if they do not exist then there execute the other query to enter the data.

    
answered by 20.06.2018 в 20:15