What are the potential security risks of not using prepared statements in PHP for database queries?
When not using prepared statements in PHP for database queries, the code is vulnerable to SQL injection attacks. This means that malicious users can manipulate input data to execute unauthorized SQL commands, potentially accessing or modifying sensitive data in the database. To prevent this, always use prepared statements with parameterized queries to sanitize user input and ensure secure database interactions.
// Using prepared statements in PHP for secure database queries
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Use the results as needed
foreach ($results as $row) {
echo $row['username'] . '<br>';
}