in_array PHP Warning

0

I need to verify if at the time of inserting a new client, register.php, there is the email that has been inserted in the form or not.

  • If there is an alert message, send the focus to the input email field and do not send data.

  • If it does NOT exist, we insert it into the customer database.

InsertCustomer function (..., ..., ...):

    static public function insertarCliente($email, $nombre, $apellidos, $dni, $telefono, $password){
        $ejecucion = self::Conexion();
        $sql = "INSERT INTO clientes VALUES ('".$email."', '".$nombre."', '".$apellidos."', '".$dni."', '".$telefono."', '".$password."', 1)";
        $ok = $ejecucion->exec($sql);
        if($ok==1){
            return true;
        }else{
            return false;
        }
    }

GetEmails () function:

static public function obtenerEmails(){
    //Realizamos la consulta.
    $ejecucion = self::Conexion();
    $sql = "SELECT idemail FROM clientes;";
    $registro = $ejecucion->query($sql);
    //Creamos una array de emails.
    $emails = array();
    //Mientras haya email los guardamos...
    while($email = $registro->fetch()){
        //Array asociativo: al array $emails le pasamos el email concreto.
        array_push($emails, $email);
    }
    //Devolvemos el array de emails.
    return $emails;
}

HTML / PHP code:

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Formulario de Registro</title>
        <link rel="stylesheet" href="css/estilos_registrar.css">
        <script type="text/javascript" src="js/validar_formulario.js"></script>
    </head>

    <body background="imagenes/fondo_campo2.jpg">
        <!--<h1>Formulario de Registro</h1>-->
        <form name="miformulario" id="miformulario" action="registrar.php" method="POST" class="form-register" onsubmit="return validar_formulario();">
            <h2 class="form-titulo">CREA UNA CUENTA</h2>
            <div class="contenedor-inputs">
                <!-- Por cada etiqueta de <input> <label for="id_mismo_que_input">XXXX: </label> -->             <!-- required para HTML5 -->
                <input type="text" name="nombre" id="nombre" placeholder="Nombre" tabindex="1" class="input-2" onkeypress="return soloLetras(event);">
                <input type="text" name="apellidos" id="apellidos" placeholder="Apellidos" tabindex="2" class="input-2">
                <br/>
                <input type="text" name="idemail" id="email" placeholder="Email" tabindex="3" class="input-1">
                <br/>
                <input type="text" name="dni" id="dni" placeholder="DNI" maxlength="9" tabindex="4" class="input-2" onkeypress="return soloLetrasNumeros(event);">
                <input type="text" name="telefono" id="telefono" placeholder="Teléfono" maxlength="9" tabindex="5" class="input-2" onkeypress="return soloNumeros(event);">
                <br/>
                <input type="password" name="password" id="password1" placeholder="Contraseña" tabindex="6" class="input-2">
                <input type="password" name="password" id="password2" placeholder="Repetir contraseña" tabindex="7" class="input-2">
                <br/>
                <input type="submit" value="Registrar" name="registrar" class="registrar" tabindex="8"/>
                <?php
                include "Clases/BD.php";
                //Si pulsamos el botón "Registrar"...
                if(isset($_POST["registrar"])){
                    $nombre = $_POST["nombre"];
                    $apellidos = $_POST["apellidos"];
                    $dni = $_POST["dni"];
                    $telefono = $_POST["telefono"];
                    $idemail = $_POST["idemail"];
                    $password = $_POST["password"];

                    $idemails = BD::obtenerEmails();
                    if(!in_array($idemail, $idemails)){
                        //Llamamos al método "insertarCliente" y le pasamos los parámetros del formulario.
                        BD::insertarCliente($idemail, $nombre, $apellidos, $dni, $telefono, $password);
                        header ("Location: si.php");
                    }else{
                        header ("Location: no.php");
                    }
                }
                ?>
                <p class="form-link">¿Ya tienes una cuenta? <a href="iniciar_sesion_cliente.php">Ingresa aquí</a></p>
            </div>
        </form>
        <!--<div class="footer">
            <p>Copyrigth</p>
        </div>-->
    </body>
</html>

Error:

Why do I always get into yes.php if there is no email in the DB?

    
asked by omaza1990 18.12.2017 в 23:20
source

1 answer

2

The problem is that your obtenerEmails function is returning an array of arrays, in the form array( array('idemail' => xx), array('idemail' => yy), ...) . Keeping your code, the easiest way to fix it is to change the function like this:

static public function obtenerEmails(){
    //Realizamos la consulta.
    $ejecucion = self::Conexion();
    $sql = "SELECT idemail FROM clientes;";
    $registro = $ejecucion->query($sql);
    //Creamos una array de emails.
    $emails = array();
    //Mientras haya email los guardamos...
    while($email = $registro->fetch()){
        //Array asociativo: al array $emails le pasamos el email concreto.
        array_push($emails, $email['idemail']);
    }
    //Devolvemos el array de emails.
    return $emails;
}

However, you could also move the test to the BdDD directly, changing to this:

static public function mailExists($email) {
   $ejecucion = self::Conexion();
   $sql = "SELECT idemail FROM clientes WHERE idemail = ?";
   $stmt = $ejecucion->prepare($sql);
   $stmt->bind_param("e", $email);
   $stmt->execute();
   return ($stmt->get_results())->num_rows!==0;
}

This function (not tested, could have a bug) should return a boolean, true if the mail already exists in the database and false if not. Use statements prepared for greater security.

    
answered by 19.12.2017 в 11:44