Home > Backend Development > PHP Tutorial > How to Reliably Run MySQL *.sql Files from PHP?

How to Reliably Run MySQL *.sql Files from PHP?

Barbara Streisand
Release: 2024-11-30 12:56:16
Original
312 people have browsed it

How to Reliably Run MySQL *.sql Files from PHP?

Running MySQL *.sql Files in PHP: An Effective Solution

Every now and then, the topic of executing MySQL .sql files from within PHP surfaces. Unfortunately, there's no straightforward solution, as .sql scripts often contain commands that cannot be executed directly as SQL statements.

The Edge Cases

Edge cases arise when *.sql scripts include built-in mysql tool commands not recognized by the MySQL server. These commands include CONNECT, TEE, STATUS, and DELIMITER.

A Reliable Approach

To address these challenges, it's recommended to invoke the mysql tool from PHP, employing a method like shell_exec(). This approach provides a robust solution for executing *.sql scripts.

Sample Code:

The following sample code demonstrates how to execute a *.sql script using shell_exec():

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

$output = shell_exec($command . '/shellexec.sql');
Copy after login

Alternative Approaches

Consider other related questions for alternative approaches to executing *.sql files:

  • Loading .sql files from within PHP
  • Is it possible to call a SQL script from a stored procedure in another SQL script?
  • PHP: multiple SQL queries in one mysql_query statement

Remember to exercise caution when using shell_exec() to prevent potential security risks.

The above is the detailed content of How to Reliably 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