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;
}
}
}
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.