Home > Backend Development > PHP Tutorial > How Can I Programmatically Execute MySQL *.sql Files in PHP?

How Can I Programmatically Execute MySQL *.sql Files in PHP?

DDD
Release: 2024-12-05 09:36:15
Original
816 people have browsed it

How Can I Programmatically Execute MySQL *.sql Files in PHP?

Executing MySQL *.sql Files Programmatically in PHP

Executing *.sql files directly from PHP through the MySQL engine's command-line interface (CLI) is not advisable due to script-specific commands such as CONNECT or DELIMITER that are not recognized by MySQL Server.

As a solution, invoke the MySQL CLI tool from PHP using methods like shell_exec(). Here's an example using shell_exec():

$command = 'mysql --host=$db_host --user=$db_user --password=$db_pass --database=$db_name --execute="SOURCE ' . $script_path;
$output1 = shell_exec($command . '/site_structure.sql"');
$output2 = shell_exec($command . '/site_db.sql"');
Copy after login

In this example, --execute="SOURCE ..." is used to specify the file to execute, instead of using the < operator. It's important to switch to the --option=value format for commands for better compatibility.

Keep in mind that the output returned by shell_exec() may not be useful, so you may need to explore alternative approaches or consult other related questions for further insights.

The above is the detailed content of How Can I Programmatically Execute MySQL *.sql Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template