How can PHP beginners effectively link and display data from different tables in a database?

To effectively link and display data from different tables in a database, beginners can use SQL JOIN statements to combine data from multiple tables based on a related column. By using JOINs, beginners can retrieve data from multiple tables in a single query and then display the results 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);
}

// Select data from multiple tables using JOIN
$sql = "SELECT users.username, orders.product_name
        FROM users
        JOIN orders ON users.id = orders.user_id";
$result = $conn->query($sql);

// Display the data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. " - Product: " . $row["product_name"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>