How can PHP documentation and examples be utilized to troubleshoot and resolve issues with SQL queries?
Issue: When troubleshooting SQL queries in PHP, it can be helpful to refer to the PHP documentation for the mysqli or PDO extensions to understand the correct syntax and usage of SQL commands. Additionally, reviewing examples provided in the documentation can give insights into common pitfalls and best practices for writing SQL queries in PHP. Example PHP code snippet:
// Connect to the database using mysqli
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Example SQL query to retrieve data from a table
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();