Do not save Array of value 0 in the database

Asked

Viewed 42 times

0

Guys, I have a form with 'n' quantities of inputs, all with the same structure:

echo "<input name='quantidade[]' type='number'>";

When I finish the form and send it to the next page, they come to me in array, and I use this array to save the data in a Mysql database, I use this method to save in the database:

for( $i=0; $i<count($_POST['item']); $i++ ) {


    // insere no banco
    $PDO = db_connect();
    $sql = "INSERT INTO carrinho(quantidade) VALUES ('".$_POST['quantidade'][$i]."')";
    $stmt = $PDO->prepare( $sql );
    $stmt->bindParam( ':quantidade', $_POST['quantidade'][$i]  );

    if ($stmt->execute())
    {
        header('Location: index.php');
    }
    else
    {
        echo "Erro ao cadastrar";
        print_r($stmt->errorInfo());
    } 

}

It saves everything, and the data that has no value in INPUT it saves with the value 0, wanted to know how to not save the Arrays with value "0".

  • If you have more than one record the second one does not insert pq already redirects. You should not put the direct value in sql you should use the placeholder defined (:quantidade).

  • The repeat loop won’t let it refresh, and I couldn’t put the array into a defined placeholder. Ta saving all the records, perfectly, only it’s saving the values 0 of the array, only thing I didn’t want!

  • If you just want to not enter the value zero, you can make a if($_POST['quantidade'][$i] > 0){..... see that your connection is made N times pq this inside the loop should be outside. If you want to send everything in a single Insert see that answer

  • That’s right, that worked out Vlw, I was trying to write something like that and I didn’t get, THANK YOU. But the Insert is to be done 'n' number of times even, this will be my cart, where will be the temporary data of the items that are in the customer cart.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.