Kevin Heimlich Kevin Heimlich - 2 months ago 6
MySQL Question

insert key$ and $value to database form foreach

I am trying to insert data of key and value from foreach. But I am getting error saying- Notice: Array to string conversion in…..(line number 22)
but I have checked both $key and $value using var_dump and found the array values are perfect. Then whats the solution to insert this $key $value data at a time to my database? also please note when i run it, the $key value is inserting successfully in db but $value value field is getting blink and getting same error in browser. you can check my db table in attached picture if required

foreach ($_POST['qty'] as $key => $value) {
mysqli_query($conn, "INSERT INTO combine (rand_id,product_id,product_qty)VALUES('$rand_id','$key','$value')");
}


enter image description here

print_r($_POST['qty']); result

Answer

As per your array and error message $value is not a string, its an array, you can get the value from $value by using one more foreach().

Example:

foreach ($_POST['qty'] as $key => $value) {
  foreach ($value as $finalVal) {
    $include[] = "('$rand_id','$key','$finalVal')";
  } 
}
$values = implode(",", $include);

$query = "INSERT INTO combine (rand_id,product_id,product_qty) VALUES $values";

Also note that, you can INSERT values in one single query as given example. Store all values in an array and than implode() with comma.

In last, your code is open for SQL Injection, you need to prevent your code. You can follow this post: How can I prevent SQL-injection in PHP? Yes Prepared Statements & Parameterized Queries is the best option for preventing.

Comments