Executing MySQL SQL Files from PHP
When developing PHP applications, you may encounter scenarios where you need to dynamically create databases and load data from SQL files. This guide will demonstrate how to execute MySQL SQL files directly from within PHP.
Step 1: Establishing a Database Connection
To execute SQL statements from PHP, you'll need to establish a connection to the MySQL database using PDO (PHP Data Objects). The following code snippet shows an example:
$dsn = 'mysql:dbname=my_database;host=localhost'; $user = 'root'; $password = 'my_password'; $db = new PDO($dsn, $user, $password);
Step 2: Loading the SQL File
Once the connection is established, you can proceed to load the SQL file. This can be done by reading the contents of the file into a string:
$sql = file_get_contents('file.sql');
Step 3: Executing the SQL Queries
Unlike phpMyAdmin's import command, which handles multiple queries per line, PHP cannot execute multiline SQL statements in a single query. Therefore, you need to iterate over the contents of the SQL file and execute each query separately:
$qr = $db->exec($sql);
Complete Code:
Combining the above steps results in the following code that will successfully load the contents of an SQL file into a MySQL database:
$dsn = 'mysql:dbname=my_database;host=localhost'; $user = 'root'; $password = 'my_password'; $db = new PDO($dsn, $user, $password); $sql = file_get_contents('file.sql'); $qr = $db->exec($sql);
The above is the detailed content of How to Execute MySQL SQL Files from PHP?. For more information, please follow other related articles on the PHP Chinese website!