Introduction:
Automating database setup for new websites is a common task in web development. This question explores how to execute multiple *.sql files from PHP, allowing for automated site generation.
Method:
The recommended method is to invoke the mysql tool via PHP using shell_exec(). This approach provides a robust solution for executing complex *.sql scripts.
Example Code:
$command = 'mysql' . ' --host=' . $vals['db_host'] . ' --user=' . $vals['db_user'] . ' --password=' . $vals['db_pass'] . ' --database=' . $vals['db_name'] . ' --execute="SOURCE ' . $script_path ; $output1 = shell_exec($command . '/site_db.sql"'); $output2 = shell_exec($command . '/site_structure.sql"');
Note:
Alternatively, you can also use the following command syntax:
$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' " . "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";
Additional Considerations:
Using the --execute="SOURCE ..." option allows for direct execution of the files, while the use of '<' may encounter compatibility issues.
Related Questions:
The above is the detailed content of How to Execute Multiple *.sql Files in PHP for Automated Database Setup?. For more information, please follow other related articles on the PHP Chinese website!