Insert PHP array into MySQL table
from the Artful MySQL Tips List
It requires a PHP array and a MySQL table, each with the same number of columns, each array column compatible with the respective table column with respect to whether its values need to be quoted in SQL statements.
For example if table tbl
has two columns, the first INT
and the second CHAR
, and you have a PHP array a
of values for it, you'd write this in PHP...
<?php>
$qry= "INSERT INTO tbl VALUES ";
foreach( $a as $row ) $qry .= sprintf( "(%s,'%s'),", $row[0], $row[1] ); // each row
$qry = substr( $qry, 0, -1 ); // remove last comma
$res = mysql_query( $qry );
?>
Return to the Artful MySQL Tips page