What best practices should be followed when handling database connections and queries in PHP to avoid errors like "Datenbank nicht erreichbar"?
When handling database connections and queries in PHP, it is important to properly handle errors to avoid issues like "Datenbank nicht erreichbar" (Database not reachable). To prevent this error, you should always check the connection status before executing queries and handle any potential errors gracefully by using try-catch blocks.
<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute query
try {
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["name"];
}
} else {
echo "0 results";
}
} catch (Exception $e) {
echo "Error executing query: " . $e->getMessage();
}
// Close connection
$conn->close();
?>
Related Questions
- What are some best practices for managing cookies in PHP to avoid compatibility issues across different domains?
- What are best practices for concatenating variables with strings in PHP, specifically for defining file paths?
- What are the limitations of using the "accept" attribute in HTML for restricting file types in PHP forms?