What are the common mistakes beginners make when trying to output database values in PHP?

Common mistakes beginners make when trying to output database values in PHP include not properly connecting to the database, not executing the query correctly, and not fetching the results in a usable format. To solve these issues, ensure you establish a connection to the database, execute the query using a database-specific function, and fetch the results in a way that can be easily displayed on the webpage.

// 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);
}

// Execute the query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Fetch and output the results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

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