Shanna Chambers Shanna Chambers - 3 months ago 11
PHP Question

passing multidimensional array to mysql using generated input fields

<?php

if (isset ($_POST['submit'])){


$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);


$query="INSERT INTO athletes (name, sports) VALUES ('".$data."')";

$result = mysqli_query($dbc, $query);

mysqli_free_result( $result);


}

?>


getting error array to string conversion.
hot do i pass that in the database in separate rows.
the output is working wonderfully when i dump just the way i want it but i cant seem to get it passed to the database.

Answer

I think you don't need to make multidimensional array name[][], you just use name[] so in your PHP code it is just like,

$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
    $myArray = explode(',', $name[$x]);// you can use your own filter for names          
    foreach($myArray as $nm){
        $data[]=array('name'=>$nm,'sports'=>$sports[$x]);
    }
}
var_dump($data);

Demo

You can change $data while inserting in database like,

$data[]='("'.trim($nm).'","'.trim($sports[$x]).'")';

And after your loop ends you can create query like,

$sql ="INSERT INTO <table> (name,sports) VALUES ".implode(',',$data);

Demo with Query