In the context of PHP and MySQL, how can developers optimize their code to prevent security vulnerabilities such as SQL injection?
Developers can prevent SQL injection by using prepared statements with parameterized queries in PHP. This method separates SQL logic from user input, preventing malicious SQL code from being executed.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', '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 statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related questions
-
PHP CSS page breaks
-
PHP str_replace database
-
foreach PHP warning