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