Home >Backend Development >PHP Tutorial >How Can I Run MySQL .sql Files from PHP?

How Can I Run MySQL .sql Files from PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 13:18:12176browse

How Can I Run MySQL .sql Files from PHP?

Running MySQL *.sql Files from PHP

Executing .sql files from within PHP can present challenges, particularly when automating site generation. While there's no direct way to execute .sql scripts in PHP, invoking the MySQL tool using shell_exec() can provide a solution.

Shell Execution Method

Using shell_exec(), you can construct a command that calls the mysql tool with appropriate flags and parameters:

$command = 'mysql'
        . ' --host=' . $vals['db_host']
        . ' --user=' . $vals['db_user']
        . ' --password=' . $vals['db_pass']
        . ' --database=' . $vals['db_name']
        . ' --execute="SOURCE ' . $script_path;

Passing the filename with --execute="SOURCE ..." ensures the file is executed. However, note that using shell_exec() requires you to provide console access, which may not be available in certain environments.

Alternative Method

For a more flexible solution that works on both Windows and UNIX platforms, you can use the following command:

$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
 . "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";

This command directly invokes the .sql file using the less-than operator (<). It doesn't require console access and provides a reliable method for executing .sql files from PHP scripts.

The above is the detailed content of How Can I Run MySQL .sql Files from PHP?. 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