Home >Backend Development >PHP Tutorial >How to Efficiently Insert PHP Array Data into a MySQL Database?
Integrating Array Data into MySQL Databases using PHP
Inserting arrays into MySQL databases presents a unique challenge due to the incompatibility between PHP data structures and SQL syntax. Unlike PHP, which operates with arrays, MySQL requires data in the form of SQL statements.
To resolve this, the key is converting the array into an INSERT statement compatible with MySQL. While splitting the array is not necessary, as suggested earlier, converting it into a valid SQL statement is crucial.
Here's a complete solution for inserting an array into a MySQL table:
$link = mysqli_connect($url, $user, $pass, $db);
$escaped_values = array_map(array($link, 'real_escape_string'), array_values($insData));
$columns = implode(", ", array_keys($insData)); $values = implode("', '", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ('$values')";
mysqli_query($link, $sql);
This code takes your provided $insData array, sanitizes its values against SQL injections, and generates a valid INSERT statement. It then executes the statement, effectively inserting the array data into the MySQL table fbdata.
The above is the detailed content of How to Efficiently Insert PHP Array Data into a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!