0

I use to insert records into mysql using prepared statement,for non-array value the below code is fine but for the array types posted it gives me the error:

Array to string conversion

index.php

<input type="text" name="test[]" /> 
<input type="text" name="test1[]" />

OUT PUT

 [test] => Array ( [0] => 1 ) [test1] => Array ( [0] => 2 )

PHP insert ( the posted data is in array )

$test=array_map('trim',$_POST["test"]);
$test1=array_map('trim',$_POST["test1"]);

$stmt = $conn->prepare("INSERT INTO test(v1,v2) VALUES (?,?)");
stmt->bind_param("ss",$test,$test1)
stmt->execute();

Now,please help how to insert array data posted html forms using prepared statement into mysql. later I need to record multiple rows using prepared statement. thanks

1 Answers1

1

Try this:

$test=array_map('trim',$_POST["test"]);
$test1=array_map('trim',$_POST["test1"]);

$stmt = $conn->prepare("INSERT INTO test(v1,v2) VALUES (?,?)");
$error=false;
foreach($test AS $key=>$value){
    if(! stmt->execute([$value,$test1[$key]])){
       $error=true;  
       break;
    }
}
if($error) // handle error

Running queries in loops like this is what prepared statements are for.

AntG
  • 1,291
  • 2
  • 19
  • 29