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
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();
?>
In this code:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3