php - Insert Multiple not empty

974

I need to insert multple records i have this right now. Its adds also the empty field because i dont know how to exclude them from inserting:

 if ($_SERVER['REQUEST_METHOD'] == 'POST'){

/* as_factuurregel */
$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];

$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];

$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
  VALUES ('$product1', 'test', '$aantal1'),('$product2', 'test', '$aantal2'),('$product4', 'test', '$aantal3'),('$product5', 'test', '$aantal5'),('$product5', 'test', '$aantal5')";

Thanks for helping.

Greetings

515

Answer

Solution:

Try this:

$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];

$array_one = array($product1,$product2,$product3,$product4,$product5,$product6);

$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];

$array_two = array($aantal1,$aantal2,$aantal3,$aantal4,$aantal5,$aantal6);

$newArray = array();
foreach ($array_one as $key => $value) {
    if($value != '' && $array_two[$key] != '')
    {
        $newArray[] = "('$value','test','$array_two[$key]')";
    }
}

$values = implode(",",$newArray);
$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
        VALUES ".$values;

You can optimize this solution if you optimize your input fields and move them in anarray.

People are also looking for solutions to the problem: php - Something went wrong while installing sample data. Please check var/log/system.log for details during Magento installation

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.