How can proper error handling and debugging techniques help identify issues in PHP code, especially when working with databases?
Proper error handling and debugging techniques in PHP can help identify issues in code by providing detailed error messages that pinpoint the problem. When working with databases, these techniques can help catch syntax errors, connection problems, or data retrieval issues. Utilizing functions like error_reporting(), try-catch blocks, and logging can aid in troubleshooting and resolving database-related errors.
// Enable error reporting to display detailed error messages
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Connect to the database and handle any connection errors
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
exit;
}
// Query the database and handle any query errors
try {
$stmt = $pdo->query("SELECT * FROM mytable");
while ($row = $stmt->fetch()) {
// Process data here
}
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
}