How can PHP beginners avoid common pitfalls when querying MySQL data for JSON conversion in PHP?

When querying MySQL data for JSON conversion in PHP, beginners often overlook properly handling errors, sanitizing input data, and ensuring proper encoding for JSON output. To avoid common pitfalls, beginners should use prepared statements to prevent SQL injection attacks, handle exceptions to catch any errors during the query execution, and use functions like json_encode() to properly convert the data to JSON format.

// Example PHP code snippet to query MySQL data and convert it to JSON format
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $stmt = $pdo->prepare("SELECT * FROM mytable");
    $stmt->execute();
    
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if ($result) {
        $json_output = json_encode($result);
        echo $json_output;
    } else {
        echo json_encode(array('error' => 'No data found'));
    }
} catch (PDOException $e) {
    echo json_encode(array('error' => 'Database error: ' . $e->getMessage()));
}