How can PHP be utilized to filter and display specific data from multiple tables based on a common attribute like a user ID or name?
To filter and display specific data from multiple tables based on a common attribute like a user ID or name in PHP, you can use SQL queries with JOIN operations to retrieve the relevant data. By joining the tables on the common attribute, you can fetch the required information and then display it using PHP.
<?php
// Connect 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);
}
// Query to fetch data from multiple tables based on a common attribute
$sql = "SELECT users.name, orders.order_id, orders.total_amount
FROM users
INNER JOIN orders ON users.user_id = orders.user_id
WHERE users.user_id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "User: " . $row["name"]. " - Order ID: " . $row["order_id"]. " - Total Amount: " . $row["total_amount"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some potential pitfalls when working with arrays in PHP forms?
- How can PHP developers ensure compatibility with older PHP versions when using newer functions or libraries that may not be available in the current PHP environment?
- What are the differences between accessing objects and arrays in PHP, and how can these differences impact data retrieval and manipulation?