What are some best practices for debugging PHP scripts that involve database interactions, especially when encountering unknown errors?
Issue: When debugging PHP scripts that involve database interactions and encountering unknown errors, it is essential to check for syntax errors, connection issues, and properly handle SQL queries and results. Fix:
<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute SQL query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Check for errors in query execution
if (!$result) {
die("Error in query: " . $conn->error);
}
// Fetch and display results
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
// Close connection
$conn->close();
?>
Keywords
Related Questions
- What are alternative methods to the header function for redirecting in PHP, and when should they be used instead?
- What are common pitfalls when working with arrays in PHP, especially when trying to insert data into a database?
- How can the issue of "Undefined index" be resolved when accessing values from a database query in PHP?