What are some common errors or pitfalls when fetching database values in PHP and how can they be avoided?
Common errors when fetching database values in PHP include not sanitizing user input, not handling errors properly, and not using prepared statements to prevent SQL injection attacks. To avoid these pitfalls, always sanitize user input using functions like mysqli_real_escape_string(), handle errors with try-catch blocks, and use prepared statements with placeholders when querying the database.
// Example of fetching database values with prepared statements and error handling
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a statement with a placeholder
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters
$stmt->bind_param("s", $username);
// Set the username variable
$username = "john_doe";
// Execute the statement
$stmt->execute();
// Get the result
$result = $stmt->get_result();
// Fetch the values
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row['username'] . "<br>";
}
// Close the statement and connection
$stmt->close();
$mysqli->close();