Welcome back to CodeYourCraft! Today, we're diving into PHP MySQLi Multi Queries. This lesson is designed for both beginners and intermediate learners, so let's get started! π
Multi Queries allow you to execute multiple SQL statements in a single PHP script. This can save time and resources, especially in applications where multiple database operations are common. π‘
To use Multi Queries, we'll be using the mysqli_multi_query() function in PHP. Let's start with a simple example.
<?php
$conn = new mysqli("localhost", "username", "password", "database");
// Multi Query Example
if ($conn->multi_query("CREATE TABLE users (id INT, username VARCHAR(30), email VARCHAR(50))")) {
echo "Table created successfully.";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>In this example, we're creating a users table with three columns: id, username, and email. Since we're using Multi Queries, we're able to create the table with a single PHP script.
<?php
$conn = new mysqli("localhost", "username", "password", "database");
// Multi Query Example
if ($conn->multi_query("INSERT INTO users (id, username, email) VALUES (1, 'john', 'john@example.com');
UPDATE users SET email = 'john@newemail.com' WHERE id = 1")) {
echo "Data inserted and updated successfully.";
} else {
echo "Error updating data: " . $conn->error;
}
$conn->close();
?>In this example, we're inserting a new user with ID 1, username john, and email john@example.com. We're also updating the email of the user with ID 1 to john@newemail.com.
What is the purpose of PHP MySQLi Multi Queries?
That's all for today! Stay tuned for more lessons on PHP and MySQL. Happy coding! π