Importing a .sql File into a MySQL Database Using PHP
When attempting to import a .sql file into a MySQL database through PHP, you may encounter the error: "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.". This error typically arises due to a deprecated MySQL extension or incorrect usage.
The deprecated mysql_* extension has been removed in PHP 7.0.0, rendering it unavailable for use. As suggested in the PHP documentation, it is recommended to employ the mysqli or PDO_MySQL extension as an alternative.
Alternatively, you can utilize the following code snippet to import a .sql file:
<code class="php"><?php // File name $filename = 'churc.sql'; // MySQL host $mysql_host = 'localhost'; // MySQL username $mysql_username = 'root'; // MySQL password $mysql_password = ''; // Database name $mysql_database = 'dump'; // Connect to MySQL server mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error()); // Select database mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error()); // Declare variables $templine = ''; $lines = file($filename); // Iterate through file lines foreach ($lines as $line) { // Ignore comments and empty lines if (substr($line, 0, 2) == '--' || $line == '') { continue; } // Append line to temporary query $templine .= $line; // Check for semicolon to mark end of query if (substr(trim($line), -1, 1) == ';') { // Execute query and handle errors mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />'); // Reset temporary query $templine = ''; } } // Success message echo "Tables imported successfully"; ?></code>
This approach connects to the MySQL server, selects the database, and iterates through the .sql file line by line, executing the encountered queries. It provides error handling and prints a success message upon successful import.
The above is the detailed content of How to Import a .sql File into a MySQL Database Using PHP Without Encountering Errors?. For more information, please follow other related articles on the PHP Chinese website!