1

I am having some issues with submitting an array of inputs to the database.

More specifically I am getting this error "Array to string conversion" on the line where I bind the parameters. How would I submit the array through the foreach loop so that they are all individual of each other.

Here is the form

<form name = "entries" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">  
<input type="text" class="form-control input-lg" name="myInputs[]">
<input type="text" class="form-control input-lg" name="myInputs[]">
<input type="text" class="form-control input-lg" name="myInputs[]">
<input id = "submit1" name="submit1" type="submit">

and here is the php

    $inputs = (empty($_POST['myInputs'])) ? : $_POST['myInputs'] ;
    foreach ((array)$inputs as $eachInput) {
        $query = $db->prepare("INSERT INTO `entries` (entries) VALUES(:inputs)");
        $query->bindParam(':inputs', $inputs, PDO::PARAM_STR);
        $query->execute();
    }

1 Answer 1

1

Please try to replace your PHP code with below code.

$inputs = $_POST['myInputs'];
if(count($inputs) > 0) {
    foreach ($inputs as $eachInput) {
        $query = $db->prepare("INSERT INTO `entries` (entries) VALUES(:inputs)");
        $query->bindParam(':inputs', $eachInput, PDO::PARAM_STR);
        $query->execute();
    }
}

If any query then let me know.

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

2 Comments

Thanks man, you're awesome. Why did I have to change it from $inputs = (empty($_POST['myInputs'])) ? : $_POST['myInputs'] ; to $inputs = $_POST['myInputs']; though? thats the only part I don't understand
@user3594895 I just make it in proper way. If you got blank array then doesn't need to run foreach loop. your code is also right :)

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.