user3594895 user3594895 - 8 days ago 5
PHP Question

Submitting array to database

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();
}

Answer

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.

Comments