0

How would I go by inserting a assoc array into a MySQL database.

When I print_r($_POST), I get this:

Array
(
    [first_name] => Array
        (
            [0] => James
            [1] => Will
            [2] => Jackie
        )

    [last_name] => Array
        (
            [0] => Bond
            [1] => Smith
            [2] => Chan
        )
)

What I have in mind is something like this.

INSERT INTO actors(first_name, last_name) VALUES ('val1','val2'), ('val1','val2'), ('val1', ....

or something like this.

$sql="INSERT INTO actors(first_name, last_name)VALUES(:first_name,:last_name)";
$stmt=$db->prepare($sql);
$stmt->bindValue(':first_name', $_POST['first_name']);//Here I get a "Array to string conversion" error 
$stmt->bindValue(':last_name', $_POST['last_name']);// Here I get a "Array to string conversion" error

foreach($_POST as $row){
$stmt->execute($row);//Here I get a "PDOStatement::execute() expects parameter 1 to be array, string given" error
}

I know there are many questions similar to this, I have viewed them all and tried the ones I could understand.

Here is the html form I'm trying to use to post to the database:

<form method="post">
    <input type="text" name="first_name[]" placeholder="First Name"/>
    <input type="text" name="last_name[]" placeholder="Last Name"/>
    <input type="text" name="first_name[]" placeholder="First Name"/>
    <input type="text" name="last_name[]" placeholder="Last Name"/>
    <input type="text" name="first_name[]" placeholder="First Name"/>
    <input type="text" name="last_name[]" placeholder="Last Name"/>
    <input type="submit" name="add_actor" value="Submit"/>
</form>
14
  • Hi, why don't u just loop ur values $stmt->bindValue(':first_name', $_POST['first_name']);$stmt->bindValue(':last_name', $_POST['last_name']); .. Doesn't it work ? Commented Nov 13, 2015 at 10:15
  • I get a "Array to string conversion" error with and without loop Commented Nov 13, 2015 at 10:23
  • even in the loop ?? Once try like this.. foreach($_POST['first_name'] as $key=>$value){$stmt->bindValue(':first_name', $value);$stmt->bindValue(':last_name', $_POST['last_name'][$key]);} Commented Nov 13, 2015 at 10:26
  • We getting close :D. Commented Nov 13, 2015 at 10:30
  • But now I get :first_name and not the value Commented Nov 13, 2015 at 10:30

5 Answers 5

3

How about something like

foreach($_POST["first_name"] as $k=>$v){

  $f_name = $v;
  $l_name = $_POST["last_name"][$k];

  $sql="INSERT INTO actors(first_name, last_name)VALUES($f_name, $l_name)";
  // James Bond
}

I would do some sort of validation however to count the values being posted.

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

1 Comment

Looping a query is not a feasible solution
1

This is what you want!

$sql="INSERT INTO actors(first_name, last_name)VALUES";

do{
    $actors_name = array_shift($_POST['first_name']);
    $actors_surname = array_shift($_POST['last_name']);
    if($actors_name || $actors_surname)
        $sql.="(".mysqli_real_escape_string($actors_name).",".
                mysqli_real_escape_string($actors_surname)."),";
}
while($actors_name || $actors_surname);

//CUT LAST COMMA FOR A CORRECT QUERY
$sql = substr($sql, 0, -1);

2 Comments

mh i probably misunderstood
using json_encode, I get a value like ["james"] in my table
0

I'll change how you pass data, setting index before parameter name

<form method="post">
    <input type="text" name="[0][first_name]" placeholder="First Name"/>
    <input type="text" name="[0][last_name]" placeholder="Last Name"/>
    <input type="text" name="[1][first_name]" placeholder="First Name"/>
    <input type="text" name="[1][last_name]" placeholder="Last Name"/>
    <input type="text" name="[2][first_name]" placeholder="First Name"/>
    <input type="text" name="[2][last_name]" placeholder="Last Name"/>
    <input type="submit" name="add_actor" value="Submit"/>
</form>

Now you can correctly execute statement:

foreach($_POST as $row){
$stmt->execute($row);//Here I get a "PDOStatement::execute() expects parameter 1 to be array, string given" error
}

1 Comment

this would work ...but not for those fields that are added dynamically with javascript.
0

you need to use a for loop to iterate the the arrays in unison. pretty simple stuff here. $i is an integer that increments, so its always selecting the next incremental row. 1 problem is that the indexes will be out of order on one side if any of the fields were left blank, so this design is flawed from the jump.

$sql="INSERT INTO actors(first_name, last_name)VALUES(:first_name,:last_name)";

$num_rows = count($_POST['first_name']) + count($post['last_name']) / 2;

for($i=0;$i<$num_rows;$i++)
{   
    $stmt=$db->prepare($sql);
    $stmt->bindValue(':first_name', $_POST['first_name'][$i]);
    $stmt->bindValue(':last_name', $_POST['last_name'][$i]);
    $stmt->execute();
}

1 Comment

is this tested? I get errors Invalid parameter number: parameter was not defined. if try $stmt->execute($sql); then I get errors saying Undefined offset: 1 and PDOStatement::execute() expects parameter 1 to be array
0

I assume that your first name and last name values are on the same indexes but on different arrays so you can concat them using array_map function something like

$array1 = array('first' => array('basheer','salman'));
$array2= array('lastname' => array('kahn','ali'));

$result_array = array();

array_map('concate', $array1, array_values($array2));
function concate($array1, $array2){
    global $result_array;
    foreach($array1 as $key => $val) {
        $result_array[] = '(' . $val . ',' . $array2[$key] . ')';
    }
}
print_r(implode(',',$result_array));//(basheer,kahn),(salman,ali)

And your sql query will look like something

INSERT INTO actors(first_name, last_name) VALUES implode(',', $result_array)

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.