What are the potential risks of SQL injection when querying a database in PHP?
SQL injection is a security vulnerability that allows attackers to execute malicious SQL queries by manipulating user input. To prevent SQL injection in PHP, you should always use prepared statements with parameterized queries instead of directly concatenating user input into SQL queries. This helps to sanitize user input and prevents attackers from injecting malicious SQL code.
// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
// Fetch data from the query result