Home >Backend Development >PHP Tutorial >How to Insert a PHP Array into a MySQL Database?
Question:
How can I insert an array into a MySQL database using PHP?
Answer:
Inserting an array directly into MySQL is not possible as MySQL only recognizes SQL statements. To store the array, it must first be converted.
Conversion and Insertion Process:
Extract Array Information:
Create SQL Statement:
Construct an INSERT statement with the column names and values as follows:
Secure Input:
Convert Array to SQL String:
Execute the INSERT Query:
Example Code:
Assuming you have a table named fbdata with columns corresponding to the array keys, the following code snippet demonstrates the process:
// Extract array information $columns = implode(", ", array_keys($insData)); // Connect to the database $link = mysqli_connect($url, $user, $pass, $db); // Escape array values $escaped_values = array_map(array($link, 'real_escape_string'), array_values($insData)); // Implode escaped values into a string $values = implode("', '", $escaped_values); // Construct the INSERT statement $sql = "INSERT INTO `fbdata`($columns) VALUES ('$values')"; // Execute the query mysqli_query($link, $sql);
The above is the detailed content of How to Insert a PHP Array into a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!