What are potential pitfalls when using PHP to fetch and display database results?
One potential pitfall when using PHP to fetch and display database results is SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to sanitize user input and prevent malicious SQL queries from being executed.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the parameter
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch and display the results
while ($row = $stmt->fetch()) {
echo $row['username'] . "<br>";
}
Related questions
-
SQL query elements arrangement
-
PHP SQL query error message
-
error reporting debugging PHP