How can one optimize the code provided to prevent it from malfunctioning in PHP?
The issue with the provided code is that it does not properly handle errors that may occur during the execution of the SQL query. To prevent the code from malfunctioning, we should use error handling techniques such as try-catch blocks to catch any exceptions that may be thrown.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Keywords
Related Questions
- How can setting the ErrorReporting and display_errors parameters in PHP help in debugging code issues?
- What is the purpose of using "ob_start();" at the beginning of a PHP script, and how does it help resolve header modification errors?
- How can the results be displayed on the current page without reloading after sending data to an external form using PHP?