What potential security risks should be considered when retrieving and displaying data from a database in PHP?
When retrieving and displaying data from a database in PHP, one potential security risk to consider is SQL injection. To prevent this, always use prepared statements with parameterized queries to sanitize user input and avoid directly inserting user input into SQL queries. Example PHP code snippet using prepared statements to retrieve and display data from a database securely:
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=my_database", "username", "password");
// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
// Bind the parameter
$stmt->bindParam(':id', $user_id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch the results
$user = $stmt->fetch();
// Display the user data
echo "Username: " . htmlspecialchars($user['username']);
echo "Email: " . htmlspecialchars($user['email']);
Related questions
-
recursion PHP Sudoku puzzle
-
str_contains PHP spam protection
-
PHP version differences