How can PHP beginners avoid errors when trying to extract specific data from a database using PHP functions?

PHP beginners can avoid errors when trying to extract specific data from a database by ensuring they are using the correct PHP functions for database interaction, such as mysqli or PDO. They should also properly handle errors and exceptions to troubleshoot issues effectively. Additionally, beginners should sanitize user input to prevent SQL injection attacks.

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

// Query to extract specific data from a table
$sql = "SELECT column1, column2 FROM table WHERE condition";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>