What is the purpose of using JOIN in MySQL queries?
When working with relational databases like MySQL, JOIN is used to combine rows from two or more tables based on a related column between them. This allows us to retrieve data from multiple tables in a single query, avoiding the need for multiple separate queries. JOIN helps in fetching related data efficiently and effectively, making it a powerful tool for querying databases.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query using JOIN to retrieve data from multiple tables
$sql = "SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Order ID: " . $row["order_id"]. " - Customer Name: " . $row["customer_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How important is it to provide code examples and context when seeking help in PHP forums to receive accurate and helpful responses?
- What are the advantages of using $_POST["ano"] over $ano in PHP form processing?
- How can PHP developers balance the need for customization and functionality in PHP scripts like osCommerce with the importance of maintaining security and data integrity?