What are the common pitfalls to avoid when using PHP to retrieve and display data from multiple tables in a database?
One common pitfall to avoid when using PHP to retrieve and display data from multiple tables in a database is not properly handling database connections and queries. It is important to establish a secure and efficient connection to the database, as well as correctly structure SQL queries to retrieve data from multiple tables. Additionally, it is crucial to properly sanitize user input to prevent SQL injection attacks.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve and display data from multiple tables
$sql = "SELECT users.username, orders.order_id FROM users INNER JOIN orders ON users.user_id = orders.user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();