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>
This code provides a reliable method for loading SQL files in PHP:
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!