What are the best practices for handling dynamic variables in PHP when retrieving data from a database?
When handling dynamic variables in PHP when retrieving data from a database, it is important to use prepared statements to prevent SQL injection attacks. This involves using placeholders in the SQL query and binding the dynamic variables to those placeholders before executing the query.
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the dynamic variable to the placeholder
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results and do something with them
foreach ($results as $row) {
echo $row['username'] . "<br>";
}