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

9
  • 2
    Possible duplicate of insert multiple rows via a php array into mysql Commented Nov 28, 2018 at 11:54
  • you can't bind an array to parameter ... Commented Nov 28, 2018 at 11:54
  • freyBake please let me know how do then? Commented Nov 28, 2018 at 11:56
  • foreach loop -> using value as the parameter bound Commented Nov 28, 2018 at 11:57
  • Leg Nurutdinov, I search alot but could not find the exact solution for my case, please put your answer if possible. thanks Commented Nov 28, 2018 at 11:57

1 Answer 1

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.

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

1 Comment

Thanks antG, its exactly what I need.

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.