What are best practices for executing SQL statements in PHP?
When executing SQL statements in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Prepared statements separate the SQL query from the user input, ensuring that input is treated as data rather than executable code. This helps to protect against malicious input and can also improve the efficiency of executing the same query multiple times.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
echo $row['username'] . '<br>';
}