How can temporary tables be created and utilized in PHP when working with MySQL queries?
To create and utilize temporary tables in PHP when working with MySQL queries, you can use the "CREATE TEMPORARY TABLE" statement to create a temporary table and then perform operations on it like a regular table. Temporary tables are only visible within the current session and are automatically dropped when the session ends.
// Create a temporary table in MySQL using PHP
$query = "CREATE TEMPORARY TABLE temp_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
)";
// Execute the query
$result = mysqli_query($connection, $query);
// Utilize the temporary table for further operations
// For example, insert data into the temporary table
$insertQuery = "INSERT INTO temp_table (name) VALUES ('John')";
$result = mysqli_query($connection, $insertQuery);
// Select data from the temporary table
$selectQuery = "SELECT * FROM temp_table";
$result = mysqli_query($connection, $selectQuery);
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . "<br>";
}