What best practices should be followed when joining tables in a MySQL query in PHP?
When joining tables in a MySQL query in PHP, it is important to follow best practices to ensure efficient and secure data retrieval. This includes using proper table aliases, specifying the columns to retrieve explicitly, and using appropriate join types based on the relationship between the tables.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query with table joins
$sql = "SELECT users.name, orders.order_id
FROM users
INNER JOIN orders ON users.user_id = orders.user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Order ID: " . $row["order_id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>