Importing .sql Files into MySQL Databases Using PHP
Importing database schemas from .sql files is a common task when deploying applications. This article explores a straightforward method to achieve this using PHP, following the guidance of phpMyAdmin's import functionality.
Solution
To import an .sql file into a MySQL database from within PHP, follow these steps:
// Establish a PDO connection to the database $db = new PDO($dsn, $user, $password); // Fetch the contents of the .sql file $sql = file_get_contents('file.sql'); // Execute the SQL queries in the file $qr = $db->exec($sql);
Explanation
The PDO class provides a database object oriented interface. The file_get_contents() function is used to read the contents of the .sql file into a string variable. The exec() function executes all the SQL queries present in the file as a single transaction.
This approach ensures that all the queries in the .sql file are executed in order, as intended by the database schema. This is an effective and efficient method for initializing or updating MySQL databases dynamically from PHP applications.
The above is the detailed content of How Can I Import .sql Files into MySQL Databases Using PHP?. For more information, please follow other related articles on the PHP Chinese website!