Home > Database > Mysql Tutorial > How to Efficiently Load SQL Files into a Database Using PHP?

How to Efficiently Load SQL Files into a Database Using PHP?

Linda Hamilton
Release: 2025-01-13 07:52:41
Original
295 people have browsed it

How to Efficiently Load SQL Files into a Database Using PHP?

Use PHP to programmatically load SQL files

Creating the database programmatically in PHP is critical to the dynamic installation process. However, loading multiple SQL files into these databases can be tricky due to the presence of multi-row queries.

Question: How to efficiently load a SQL file into a database using PHP, thus replicating the functionality of the PHPMyAdmin import command?

Answer:

<code class="language-php">use PDO;

$dsn = 'mysql:host=localhost;dbname=database_name';
$user = 'username';
$password = 'password';

$db = new PDO($dsn, $user, $password);

$sql = file_get_contents('file.sql');

$qr = $db->exec($sql);</code>
Copy after login

This code provides a reliable method for loading SQL files in PHP:

  • It uses the PDO class to establish a connection to the database.
  • Get the entire contents of the SQL file and store it in the $sql variable.
  • PDO::exec() method executes the SQL statement contained in the file.

This scheme ensures correct handling of multi-line queries, allowing seamless loading of SQL files in PHP scripts.

The above is the detailed content of How to Efficiently Load SQL Files into a Database 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