Home >Backend Development >PHP Tutorial >How to Execute Multiple *.sql Files in PHP for Automated Database Setup?

How to Execute Multiple *.sql Files in PHP for Automated Database Setup?

DDD
DDDOriginal
2024-12-09 02:30:101063browse

How to Execute Multiple *.sql Files in PHP for Automated Database Setup?

Executing MySQL *.sql Files in PHP

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:

  • Loading .sql files from within PHP
  • Calling SQL scripts from stored procedures in other SQL scripts
  • Executing multiple SQL queries in a single mysql_query statement

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn