Home > Backend Development > PHP Tutorial > How to Execute MySQL SQL Files from PHP?

How to Execute MySQL SQL Files from PHP?

Barbara Streisand
Release: 2024-11-25 17:59:15
Original
812 people have browsed it

How to Execute MySQL SQL Files from PHP?

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);
Copy after login

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');
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template