How can SQL queries be stored in separate .sql files and executed in PHP?

To store SQL queries in separate .sql files and execute them in PHP, you can read the contents of the .sql file into a string variable and then execute the query using a database connection in PHP. This approach helps in separating SQL queries from PHP code for better organization and maintenance.

// Read SQL query from a .sql file
$sqlQuery = file_get_contents('path/to/query.sql');

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Execute the SQL query
if ($conn->query($sqlQuery) === TRUE) {
    echo "Query executed successfully";
} else {
    echo "Error executing query: " . $conn->error;
}

// Close the database connection
$conn->close();