In what scenarios would using SQLite be a better alternative to storing user data in text files in PHP?

Storing user data in text files in PHP can become cumbersome and inefficient as the amount of data grows. Using SQLite, a lightweight and serverless database, can offer better performance, scalability, and data management capabilities. SQLite allows for querying and manipulating data using SQL, making it easier to work with compared to parsing text files.

// Connect to SQLite database
$db = new SQLite3('userdata.db');

// Create a table to store user data
$db->exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, email TEXT)');

// Insert user data into the table
$db->exec("INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')");

// Retrieve user data from the table
$result = $db->query('SELECT * FROM users');
while ($row = $result->fetchArray()) {
    echo $row['id'] . ' - ' . $row['username'] . ' - ' . $row['email'] . '<br>';
}

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