Question

I have a table that contains a list of all products and before each one there is a field "number" in which the user will put the quantity then click on save.

This code save all rows in data base using mutiple-insert but I want that if quantite is null or empty, so do not save this row , I want just save

$managerAchat = new AchatManager($db);


if(isset($_POST['ajouter']))
{

$size = count($_POST['quantite']);

$i = 0;
while ($i < $size) 
{
if(isset($_POST['quantite'][$i]))
    {

      $nomProd = $_POST['nomProd'][$i] ;
      $prixProd = $_POST['prixProd'][$i] ;
      $quantite = $_POST['quantite'][$i] ;
      $date = date('d/m/Y');

      $AchatObject = new Achat(array(
      'nomProd' => $nomProd ,
      'prixProd' => $prixProd ,
      'quantite' => $quantite ,
      'date' => $date ,
            )) ;

      $managerAchat->insert($AchatObject);

      ++$i;
    }


}       


}
Was it helpful?

Solution

It seems you just need to change:

if(isset($_POST['quantite'][$i]))

to:

if(isset($_POST['quantite'][$i]) && $_POST['quantite'][$i] > 0)

You can also use for example array_filter() to loop only over the keys that have an amount set:

if(isset($_POST['ajouter']))
{
  $has_amounts = array_filter($_POST['quantite']);
  foreach (array_keys($has_amounts) as $key)
  {
    $nomProd = $_POST['nomProd'][$key];
    // etc.

OTHER TIPS

I'm not 100% sure this is correct as your question and code are not clear. But, you can check to see if $_POST['quantite'][$i] is empty (zero and null will both be considered empty) and skip them if they are:

if(isset($_POST['quantite'][$i]) && !empty($_POST['quantite'][$i]))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top