Pass array to SQL insert query using PHP
P粉207483087
P粉207483087 2023-08-28 21:42:59
0
1
483
<p>I have a SQL query to insert data without column names: </p> <pre class="brush:php;toolbar:false;">$sql = "INSERT INTO test_table VALUES (null,1,2,3) " if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}</pre> <p>I want to insert 1,2,3 as an array, something like this: </p> <pre class="brush:php;toolbar:false;">$data = [1,2,3]; $sql = "INSERT INTO test_table VALUES (null,$data) " if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}</pre> <p>I also tried php's implode function but it didn't work. Any help would be greatly appreciated. Thanks! </p>
P粉207483087
P粉207483087

reply all(1)
P粉343141633

You don't provide the table structure it's inserting into, but if you just want to solve the problem of splitting the $data array into its component parts, there are a few ways:

a) Use implode(), which should work fine despite you already mentioned trying it:

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

b) Quote each array index:

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

But this only works if there is a fixed number of values ​​in the array.

c) Traverse the array:

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

Hope this helps, if not please provide more details about the data being inserted and the database table structure so we can better understand the problem.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template