What are the potential pitfalls of directly outputting the result of a MySQL query in PHP without proper handling?

Directly outputting the result of a MySQL query in PHP without proper handling can lead to security vulnerabilities such as SQL injection attacks. To prevent this, you should always sanitize and escape user input before using it in a query. Additionally, you should handle errors that may occur during the query execution to provide a better user experience.

// Example of properly handling a MySQL query in PHP
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();
$result = $stmt->get_result();

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

$stmt->close();
$conn->close();