'pass array to sql insert query php

i have a sql query to insert data without col names :

$sql = "INSERT INTO test_table VALUES (null,1,2,3) ";
if (mysqli_query($conn, $sql)) {echo  'success!';}else {echo 'failed!';}

I want to insert 1,2,3 as array , something like this:

$data = [1,2,3];    
$sql = "INSERT INTO test_table VALUES (null,$data) ";
if (mysqli_query($conn, $sql)) {echo  'success!';}else {echo 'failed!';}

I tried php implode function too, but it didn't worked. Any help will be appreciated. Thank you!



Solution 1:[1]

You didn't provide the table structure that it is going into, but if all you are wanting to solve for is having the $data array split into constituent parts you could do it several ways:

a) implode(), although you already mentioned trying it, should work just fine:

$data = [1,2,3];    
$sql = "INSERT INTO test_table VALUES (null,".implode(',',$data).")";

b) reference each array index:

$data = [1,2,3];    
$sql = "INSERT INTO test_table VALUES (null,{$data[0]},{$data[1]},{$data[2]})";

That only works if you have a set amount of values in the array however.

c) loop over the array:

$data = [1,2,3];    
$sql = "INSERT INTO test_table VALUES (null"
foreach($data as $value){ $sql .= ",$value"; }
$sql .= ")";

Hope that helps, if not please provide more details about the structure of both the data going in and the database table so we can better understand the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1