How to avoid blank records to the db, in the filters the empty field is valid .. but still commands them

1
<?php 

$errores = '';
$enviado = '';



if (isset($_POST['submit'])) {
    $nombre = strtoupper($_POST['nombre']);
    $apellidopaterno = strtoupper($_POST['apellidopaterno']);
    $apellidomaterno = strtoupper($_POST['apellidomaterno']);
    $telefono = strtoupper($_POST['telefono']);
    $correo = $_POST['correo'];
    $mensaje = strtoupper($_POST['mensaje']);


try{

   $conexion = new PDO ('mysql:host=localhost;dbname=pruebas;charset=utf8', 'root', '');

    }catch (PDOException $e) {
        echo    "Error:" . $e->getMessage();
    }

    try{

        $statement = $conexion->prepare("INSERT INTO usuario(nombre,apellidopaterno,apellidomaterno,telefono,correo,mensaje)VALUES( :nombre, :apellidopaterno,:apellidomaterno, :telefono, :correo, :mensaje)");
        $statement->bindParam(':nombre', $nombre);
        $statement->bindParam(':apellidopaterno', $apellidopaterno);
        $statement->bindParam(':apellidomaterno', $apellidomaterno);
        $statement->bindParam(':telefono', $telefono);
        $statement->bindParam(':correo', $correo);
        $statement->bindParam(':mensaje', $mensaje);
        $conexion->beginTransaction();
        $statement->execute();  
        $conexion->commit();    

}catch(Exception $e) {
    $conexion->rollback();
    echo "Error: 0" . $e->getMessage();
}


    if (!empty($nombre)) {
        $nombre = trim($nombre);
        $nombre = filter_var($nombre, FILTER_SANITIZE_STRING);
    } else {
        $errores .= 'Por favor ingresa un nombre <br />';
    }


    if (!empty($apellidopaterno)) {
        $apellidopaterno = trim($apellidopaterno);
        $apellidopaterno = filter_var($apellidopaterno, FILTER_SANITIZE_STRING);
    } else {
        $errores .= 'Por favor ingresa tu apellido paterno <br />';
    }

    if (!empty($apellidomaterno)) {
        $apellidomaterno = trim($apellidomaterno);
        $apellidomaterno = filter_var($apellidomaterno, FILTER_SANITIZE_STRING);
    } else {
        $errores .= 'Por favor ingresa tu apellidomaterno<br />';
    }


    if (!empty($telefono)) {
        $telefono = trim($telefono);
        $telefono = filter_var($telefono, FILTER_SANITIZE_STRING);
    } else {
        $errores .= 'Por favor ingresa tu telefono <br />';
    }



    if (!empty($correo)) {
        $correo = filter_var($correo, FILTER_SANITIZE_EMAIL);

        if(!filter_var($correo, FILTER_VALIDATE_EMAIL)){
            $errores .= 'Por favor ingresa un correo valido <br />';
        }
    } else {
        $errores .= 'Por favor ingresa un correo <br />';
    }

    if(!empty($mensaje)){
        $mensaje = htmlspecialchars($mensaje);
        $mensaje = trim($mensaje);
        $mensaje = stripslashes($mensaje);
    } else {
        $errores .= 'Por favor ingresa el mensaje <br />';
    }




    if(!$errores){ $enviado = 'true';
    }

}


require 'index.view.php';



?>
    
asked by carlos 26.08.2018 в 16:11
source

2 answers

2

If you check the logic of your code you will see without too much difficulty that the validations are made after the INSERT, so they do not make any sense there, you should do them before . In addition, you should validate also on the client side, to avoid sending empty data to the server, but that is another issue.

I propose this code, I explain in order the logic that I have followed.

  • We set the variable $errores to an initial value NULL . It will serve as a flag to know if you acquired data or not later in if .
  • We are going to use ternary operators to store the POST variables once and for all. We will apply everything there is to apply to the data, thus avoiding the writing of so much redundant code. The only function that has any utility here on the data is trim . Functions like filter_var do not help at all here. What makes the code solid is the queries prepared when it comes to inserting data.
  • Before doing the INSERT we will ask for each variable. In the ternary operator we told the code that if any variable is empty, we assign it NULL . Therefore in the if we can evaluate simply like this: if (!$variable) { ...
  • After evaluating each variable we will ask about the state of our flag: if (!$errores){ That is, if $errores is NULL as at the beginning, it means that there are no errors, all correct, then we can move to insert .
  • At the end of that block we changed the status of $enviado=TRUE; Just for code consistency, I gave the value FALSE at the beginning.

The code would be this:

<?php

$errores = NULL;
$enviado = FALSE;

if (isset($_POST['submit'])) {
    $nombre =          (empty(trim($_POST['nombre'])))          ? NULL : strtoupper($_POST['nombre']);
    $apellidopaterno = (empty(trim($_POST['apellidopaterno']))) ? NULL : strtoupper($_POST['apellidopaterno']);
    $apellidomaterno = (empty(trim($_POST['apellidomaterno']))) ? NULL : strtoupper($_POST['apellidomaterno']);
    $telefono =        (empty(trim($_POST['telefono'])))        ? NULL : $_POST['telefono'];
    $correo =          (empty(trim($_POST['correo'])))          ? NULL : $_POST['correo'];
    $mensaje =         (empty(trim($_POST['mensaje'])))         ? NULL : strtoupper($_POST['mensaje']);

    try{

        $conexion = new PDO ('mysql:host=localhost;dbname=pruebas;charset=utf8', 'root', '');

    }catch (PDOException $e) {
        echo    "Error:" . $e->getMessage();
    }

    try{

        if (!$nombre){
            $errores .= 'Por favor ingresa tu nombre <br />';
        }

        if (!$apellidopaterno){
            $errores .= 'Por favor ingresa tu apellido paterno <br />';
        }

        if (!$apellidomaterno){
            $errores .= 'Por favor ingresa tu apellido materno <br />';
        }

        if (!$telefono){
            $errores .= 'Por favor ingresa tu teléfono <br />';
        }

        if (!$correo){
            $errores .= 'Por favor ingresa tu correo <br />';
        }

        if (!$mensaje){
            $errores .= 'Por favor ingresa un mensaje <br />';
        }

        if (!$errores){

            $statement = $conexion->prepare("INSERT INTO usuario(nombre,apellidopaterno,apellidomaterno,telefono,correo,mensaje)VALUES( :nombre, :apellidopaterno,:apellidomaterno, :telefono, :correo, :mensaje)");
            $statement->bindParam(':nombre', $nombre);
            $statement->bindParam(':apellidopaterno', $apellidopaterno);
            $statement->bindParam(':apellidomaterno', $apellidomaterno);
            $statement->bindParam(':telefono', $telefono);
            $statement->bindParam(':correo', $correo);
            $statement->bindParam(':mensaje', $mensaje);
            $conexion->beginTransaction();
            $statement->execute();
            $conexion->commit();
            $enviado=TRUE;
        }

    }catch(Exception $e) {
        $conexion->rollback();
        echo "Error: 0" . $e->getMessage();
    }


}

require 'index.view.php';



?>

There are other things that are not clear in the code, such as the reason you use transactions ... is it a massive insert or is the code a concurrent code that many users will use at the same time?

In any case, I think this code solves the problem here. If you have other problems do not hesitate to raise them by opening a new question.

If there is any doubt or error, you can say it in comments below this answer.

    
answered by 26.08.2018 / 20:50
source
-1

Hello carlos you can put in place of empty you can put strlen($var) that function returns the length of the text and so you can handle the minimum size of the variables (if you want it if you do not follow the empty) ay, otherwise the filter_var and also the trim goes outside the if that function sometimes leaves you blank texts and if within if you put this function you can add blank texts.

    
answered by 26.08.2018 в 17:00