Pass array to SQL insert query using PHP
P粉207483087
2023-08-28 21:42:59
<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>
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:
b) Quote each array index:
But this only works if there is a fixed number of values in the array.
c) Traverse the array:
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.