What are common errors when using PHP to fetch data from a MySQL database?
Common errors when using PHP to fetch data from a MySQL database include not connecting to the database properly, using incorrect SQL syntax, and not handling errors effectively. To solve these issues, ensure that you establish a connection to the database using the correct credentials, write valid SQL queries, and implement error handling to catch any potential issues.
// Establish a connection to the MySQL 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);
}
// Write a SQL query to fetch data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data from each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();