How can the code be optimized to prevent SQL injections and improve overall performance?
To prevent SQL injections and improve overall performance, you can use prepared statements in PHP. Prepared statements separate SQL code from user input, preventing malicious SQL injections. Additionally, prepared statements can be cached by the database server for improved performance.
// Using prepared statements to prevent SQL injections and improve performance
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
// Output data
echo $row['username'] . "<br>";
}