How can prepared statements or escaping functions be used in PHP to prevent SQL injection when working with SQLite databases?
SQL injection can be prevented in PHP when working with SQLite databases by using prepared statements or escaping functions. Prepared statements allow for the separation of SQL code from user input, ensuring that input is treated as data and not executable code. Escaping functions like SQLite3::escapeString() can also be used to sanitize user input before including it in SQL queries.
// Using prepared statements to prevent SQL injection in SQLite database
$db = new SQLite3('database.db');
$stmt = $db->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindValue(':username', $_POST['username']);
$result = $stmt->execute();
while ($row = $result->fetchArray()) {
// Process the retrieved data
}
$stmt->close();
$db->close();