What best practices should be followed when handling and displaying data from a database in PHP?
When handling and displaying data from a database in PHP, it is important to sanitize user input to prevent SQL injection attacks. This can be done using prepared statements with parameterized queries. Additionally, always validate and escape data before outputting it to prevent cross-site scripting attacks.
// 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 id = :id');
// Bind the parameter
$stmt->bindParam(':id', $_GET['id']);
// Execute the query
$stmt->execute();
// Fetch the results
$user = $stmt->fetch();
// Output the data after escaping it
echo htmlspecialchars($user['username']);
Related Questions
- What are the potential benefits and drawbacks of using persistent database connections in PHP scripts?
- What is the significance of using the return statement in a PHP function like dirread in the context of the code snippet?
- What are the necessary settings in PHP.ini and IIS server for successful file uploads in PHP?