How can one ensure data security when retrieving information from a database in PHP?
To ensure data security when retrieving information from a database in PHP, it is important to use prepared statements with parameterized queries to prevent SQL injection attacks. This technique helps sanitize user input and ensures that malicious SQL code cannot be injected into the query.
// Establish a database connection
$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 value
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();