Save PHP if all fields are complete

2

I have a simple html form and a php code that checks that all required fields are complete. If they are all correct, they are saved in a .txt file, if they are not, it shows an error message.

My question is how to make it just save the data in the .txt if all the fields are correct.

My idea was to make a counter, where add 1 each time an error is generated

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fail = 0;
if (empty($_POST["producto"])) {
    $prodErr ="Ingrese nombre de producto";
    $fail++;
} 
else {
    $producto = ($_POST["producto"]);
}
if (empty($_POST["cantidad"])) {
    $cantErr ="Ingrese cantidad del producto";
    $fail++;
} 
elseif ($_POST["cantidad"] < 99) {
    $cantidad = ($_POST["cantidad"]);
}
else {
    $cantErr ="Ingrese una cantidad valida 1-99";
    $fail++;
}
if (empty($_POST["precComp"])) {
    $precCompErr ="Ingrese un número";
    $fail++;
} 
else {
    $precComp = ($_POST["precComp"]);
}
if (empty($_POST["precVent"])) {
    $precVentErr ="Ingrese un número";
    $fail++;
} 
else {
    $precVent = ($_POST["precVent"]);
}
if ($fail == 0) {
        fwrite($myfile, "Producto: " .$producto. PHP_EOL ."Cantidad: ".$cantidad. PHP_EOL ."Precio Compra: " .$precComp. PHP_EOL  ."Precio Venta: " .$precVent);
        fclose($myfile);

    }       
else {} 

Then with IF statement if the counter is 0 saves the data in the .txt, ELSE does not do anything.

This is not working, if I send the form blank, or with some missing data I get the error that you enter a quantity but the file is modified.

Can you solve it? What other way is there to do this? Thanks

    
asked by Gaston Raboy 08.06.2018 в 04:53
source

1 answer

0

I see that you do not have the fopen function, on the other hand, the issue of validation and or I would do so:

$fail = false;
$producto = null;
$cantidad = null;
$precComp = null;
$precVent = null;
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["producto"])) {
    $errors[]="Ingrese nombre de producto";
    $fail=true;
} 
else {
    $producto = ($_POST["producto"]);
}
if (empty($_POST["cantidad"])) {
    $errors[] ="Ingrese cantidad del producto";
    $fail=true;
} 
elseif ($_POST["cantidad"] < 99) {
    $cantidad = ($_POST["cantidad"]);
}
else {
    $errors[] ="Ingrese una cantidad valida 1-99";
    $fail=true;
}
if (empty($_POST["precComp"])) {
    $errors[] ="Ingrese un número";
    $fail=true;
} 
else {
    $precComp = ($_POST["precComp"]);
}
if (empty($_POST["precVent"])) {
    $errors[] ="Ingrese un número";
    $fail=true;
} 
else {
    $precVent = ($_POST["precVent"]);
}
if (!$fail) {
    fopen($myfile, "a");
    fwrite($myfile, "Producto: " .$producto. PHP_EOL ."Cantidad: ".$cantidad. PHP_EOL ."Precio Compra: " .$precComp. PHP_EOL  ."Precio Venta: " .$precVent);

    fclose($myfile);

    }       
else {
   echo var_dump(errors);
} 

I hope it works for you:)

    
answered by 08.06.2018 в 09:13