Home  >  Q&A  >  body text

Pass array to SQL insert query using PHP

<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粉207483087P粉207483087418 days ago443

reply all(1)I'll reply

  • P粉343141633

    P粉3431416332023-08-29 17:56:37

    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.

    reply
    0
  • Cancelreply