What are the potential security risks of using a string directly in a SQL query in PHP?
Using a string directly in a SQL query in PHP can lead to SQL injection attacks, where an attacker can manipulate the query to execute unauthorized commands on the database. To prevent this, you should use prepared statements with parameterized queries in PHP, which separate the SQL query logic from the user input.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query with a parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter value
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();