Home > Backend Development > PHP Tutorial > How Can I Import .sql Files into MySQL Databases Using PHP?

How Can I Import .sql Files into MySQL Databases Using PHP?

Barbara Streisand
Release: 2024-11-26 04:43:14
Original
884 people have browsed it

How Can I Import .sql Files into MySQL Databases Using PHP?

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

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!

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