Importing .sql Files into MySQL Using PHP
When attempting to import a .sql file through PHP, an error may arise, indicating that the import file is not in the same folder as the script or that the values are incorrect.
Determining the Issue
The provided code executes a command using the exec() function to import the .sql file. However, the error message suggests that the import file cannot be found or that the values for the database connection are incorrect.
Alternative Approach
Rather than using the exec() function, a more reliable method is to use the MySQLi extension, which provides explicit support for MySQL database interactions in PHP.
Revised Code
<code class="php"><?php // Name of the SQL file to import $filename = 'dbbackupmember.sql'; // MySQL connection credentials $hostname = 'localhost'; $username = 'root'; $password = ''; $database = 'test'; // Create a new MySQLi connection $mysqli = new mysqli($hostname, $username, $password, $database); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; exit; } // Get the contents of the SQL file $sql = file_get_contents($filename); // Execute the SQL statements $result = $mysqli->multi_query($sql); // Check the execution status if ($result) { echo "SQL file imported successfully."; } else { echo "Error importing SQL file: " . $mysqli->error; } // Close the connection $mysqli->close(); ?></code>
In this code:
The above is the detailed content of How to Successfully Import .sql Files into MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!