Home > Article > Backend Development > How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?
How to Import a .sql File into a MySQL Database Using PHP
Importing a .sql file into a MySQL database using PHP can be easily accomplished, but requires careful attention to detail. Here's a detailed explanation:
Error Troubleshooting
Your error message indicates that the import file is not located in the same folder as your script. Ensure that the file path provided in the $mysqlImportFilename variable is correct and matches the location of your .sql file.
Alternative Approach
If you encounter issues with the exec() function, consider an alternative approach using the mysql_query() function as follows:
<code class="php"><?php // Database connection details $host = 'localhost'; $user = 'root'; $pass = ''; $db = 'test'; // Open connection $conn = mysqli_connect($host, $user, $pass, $db); // Read SQL file $sql = file_get_contents('dbbackup.sql'); // Execute SQL queries if (mysqli_multi_query($conn, $sql)) { echo 'Import file successfully imported.'; } else { echo 'Error importing file: ' . mysqli_error($conn); } // Close connection mysqli_close($conn); ?></code>
Important Notes
The above is the detailed content of How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?. For more information, please follow other related articles on the PHP Chinese website!