What are some best practices for handling variables and sessions in PHP when querying a database like SQLITE?

When handling variables and sessions in PHP when querying a database like SQLITE, it is important to properly sanitize user input to prevent SQL injection attacks. Additionally, it is recommended to use prepared statements to execute queries safely and efficiently. Finally, always close the database connection after use to free up resources.

// Sanitize user input
$user_input = filter_var($_POST['user_input'], FILTER_SANITIZE_STRING);

// Create a new database connection
$db = new SQLite3('database.db');

// Prepare a SQL statement with a placeholder
$stmt = $db->prepare('SELECT * FROM table WHERE column = :user_input');
$stmt->bindValue(':user_input', $user_input, SQLITE3_TEXT);

// Execute the query
$result = $stmt->execute();

// Fetch results
while ($row = $result->fetchArray()) {
    // Process the results
}

// Close the database connection
$db->close();