What are the best practices for efficiently importing data from a .sql file into a MySQL database using PHP?
When importing data from a .sql file into a MySQL database using PHP, it is important to use the MySQL command-line tool for efficiency. This can be achieved by executing the MySQL command within a PHP script using the shell_exec() function. By doing so, you can easily import large datasets without encountering memory or timeout issues.
<?php
// Path to the .sql file
$sqlFile = 'path/to/your/file.sql';
// MySQL database connection details
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'database_name';
// Command to import .sql file into MySQL database
$command = "mysql -h $host -u $user -p$password $database < $sqlFile";
// Execute the command using shell_exec
$output = shell_exec($command);
// Check if the import was successful
if(!$output) {
echo "Data imported successfully.";
} else {
echo "Error importing data: $output";
}
?>