Forms and Files

3

I'm making a form where I basically access a .txt file in CSV format that contains some articles and their prices (eg cheese, 2.10).

The program displays the list in a table, and below are two fields that ask for "Article" and "Quantity", now the best way to get the program to look for the article in the file, and say if it exists or not, if the product exists, display the total of the quantity multiplication with the value of the product, which is in the second column of the .txt file.

For example, Product: Cheese, Quantity: 10, present 10x the total cheese price down.

PS: Forms with the "Item" and "Quantity" fields disappear after being filled in.

So far my code looks like this:

<?php

$br="</br>";
$file=fopen("produtos.txt","r");

echo "<table border='1'><tr><th>Artigos</th><th>Preco</th>";
while(!feof($file)) {
$registo=fgetcsv($file);

    echo"<tr>";
    echo"<td>".$registo[0]."</td>";
    echo"<td>".$registo[1]."</td>";
    echo"</tr>";

}
echo "</table>";
fclose($file);
?>

<?php
if ($_POST) {
    echo "Produto: ".$_POST["produto"]."<br>";
    echo "Quantidade ".$_POST["quantidade"]."<br>";
}
else {
?>

<form action="eta15.php" method="post">
Produto <input type="text" name="produto"><br>
Quantidade <input type="text" name="quantidade"><br>
<input type="Submit" name="enviar" value="Enviar">
</form>

<?php 
}
?>

I leave two printscreens, I hope they help in my question of the result that I am:

Search form:

Resultform:

    
asked by anonymous 12.10.2016 / 16:29

2 answers

1

To do this, simply do a search condition, if the product is the same as the one searched, then calculate the total of the multiplication of the price by the quantity:

//...
$produto = isset( $_POST["produto"]    ) ? $_POST["produto"]    : "";
$qtd     = isset( $_POST["quantidade"] ) ? $_POST["quantidade"] : ""; 
$total   = 0;
$precoUN = 0;

while(!feof($file)) 
{
    $registo=fgetcsv($file);

    if( $produto == $registo[0] )
    {
        $total   = $registo[1] * $qtd;
        $precoUN = $registo[1];
    }

    echo"<tr>";
    echo"<td>".$registo[0]."</td>";
    echo"<td>".$registo[1]."</td>";
    echo"</tr>";

}
//...
if ($_POST) 
{
    echo "Produto:    ". $produto ."<br>";
    echo "Quantidade: ". $qtd     ."<br>";
    echo "Total       ". $total   ."<br>";
    echo "Preço/UN    ". $precoUN ."<br>";

    if ( $total > 0 ) 
    {
        echo "<br> O Produto selecionado existe";
    }
    else 
    { 
        echo "O Produto nao existe";
    }
}
//...
    
13.10.2016 / 12:25
-2

 I resolved with If, anything questions there!

    
12.10.2016 / 17:56