1

I use 4 input boxes with same name.I will fill only one input box at a time and insert in DB using php.But doing following method inserts three empty records along with value-filled 4 th record.Need help!

Html

                <input type="text" name="abc[]" id="abc" value=""> 
                <input type="text" name="abc[]" id="abc"  value="">
                <input type="text" name="abc[]" id="abc"  value="">
                <input type="text" name="abc[]" id="abc" value="">

Php

$abc = $_POST['abc'];
        if (is_array($abc)) {
                foreach($abc as $c) {

$insert="INSERT INTO item(productid) VALUES ('$c')";
                    $insert2=mysql_query($insert);              }

}

2 Answers 2

3

just check if the value is not empty then insert to database.

$abc = $_POST['abc'];
if (is_array($abc)) {
    foreach ($abc as $c) {
        if(!empty($c)){
            $insert = "INSERT INTO item(productid) VALUES ('$c')";
            $insert2 = mysql_query($insert);
        }
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

The following code produces 1 INSERT statement. If as you suggest you are only using 1 value from your input, and can enforce this you can omit $value = rtrim($value, ","); which removes the trailing ,.

I would also advise you to use either mysqli or PDO because mysql_functions are deprecated.

 $value = "";
if(isset($_POST['submit'])){
    if(isset($_POST['abc'])){
        foreach($_POST['abc'] as $c) {
        if(!empty($c)){
        $value .= "'".$c."',";}
        }
        $value = rtrim($value, ",");
    }
    $insert="INSERT INTO item(productid) VALUES ($value)";
    echo $insert;//Remove after testing
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.