What are some tips for troubleshooting issues with database queries in PHP?
Issue: When troubleshooting database queries in PHP, it's important to check for syntax errors, connection issues, and proper error handling to identify and resolve any problems.
// Example code snippet for troubleshooting database queries in PHP
// Establish a connection to the database
$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 a sample query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Check for errors in the query execution
if (!$result) {
die("Error in query: " . $conn->error);
}
// Fetch and display results
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"] . " - Column2: " . $row["column2"] . "<br>";
}
// Close the connection
$conn->close();