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
Release: 2024-12-01 13:18:12
Original
171 people have browsed it

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;
Copy after login

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}";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template