What potential issues can arise when using multiple tables in a database query in PHP?
One potential issue that can arise when using multiple tables in a database query in PHP is the risk of creating Cartesian products, where the result set grows exponentially due to the combination of rows from different tables. To solve this issue, you can use JOIN clauses in your SQL query to specify how the tables should be linked together based on their common columns.
<?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 JOIN clause to prevent Cartesian product
$sql = "SELECT users.username, orders.order_id
FROM users
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 "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>