Home > Article > Backend Development > How to troubleshoot errors when importing a .sql file into a MySQL database using PHP?
When attempting to import a .sql file using a PHP script, you may encounter an error. To resolve this issue, verify that the SQL file is in the same directory as the script.
Here's a modified code that should work:
<code class="php"><?php // Enter the database info $mysqlDatabaseName = 'test'; $mysqlUserName = 'root'; $mysqlPassword = ''; $mysqlHostName = 'localhost'; $mysqlImportFilename = 'dbbackupmember.sql'; // Execute the MySQL import command $command = 'mysql -h' . $mysqlHostName . ' -u' . $mysqlUserName . ' -p' . $mysqlPassword . ' ' . $mysqlDatabaseName . ' < ' . $mysqlImportFilename; exec($command, $output, $worked); // Display a message based on the import status switch($worked) { case 0: echo 'Import file <b>' . $mysqlImportFilename . '</b> successfully imported to database <b>' . $mysqlDatabaseName . '</b>.'; break; case 1: echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br /><br /><table border="1"> <tr><td>MySQL Database Name:</td><td><b>' . $mysqlDatabaseName . '</b></td></tr> <tr><td>MySQL User Name:</td><td><b>' . $mysqlUserName . '</b></td></tr> <tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr> <tr><td>MySQL Host Name:</td><td><b>' . $mysqlHostName . '</b></td></tr> <tr><td>MySQL Import Filename:</td><td><b>' . $mysqlImportFilename . '</b></td></tr> </table>'; break; } ?></code>
Avoid using the obsolete mysql_* functions. Instead, consider using either the mysqli or PDO_MySQL extensions.
The above is the detailed content of How to troubleshoot errors when importing a .sql file into a MySQL database using PHP?. For more information, please follow other related articles on the PHP Chinese website!