In the modern world, data analysis and reporting have become key factors in decision-making for businesses and individuals. PHP, as a widely used web development language, provides powerful data processing capabilities, while SQLite, a lightweight embedded database system, is ideal for small-scale applications. This article will introduce how to use PHP and SQLite together to implement data statistics and report generation, helping developers efficiently manage and present data.
<?php $db = new SQLite3('data.db'); $db->exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)'); ?>
<?php $db = new SQLite3('data.db'); $db->exec("INSERT INTO users (name, age) VALUES ('John', 25)"); $db->exec("INSERT INTO users (name, age) VALUES ('Jane', 30)"); $db->exec("INSERT INTO users (name, age) VALUES ('Mark', 35)"); $db->exec("INSERT INTO users (name, age) VALUES ('Alice', 40)"); ?>
<?php $db = new SQLite3('data.db'); $result = $db->query("SELECT COUNT(*) AS total_users, AVG(age) AS avg_age FROM users"); $row = $result->fetchArray(); echo 'Total Users: ' . $row['total_users']; echo 'Average Age: ' . $row['avg_age']; ?>
<?php $db = new SQLite3('data.db'); $result = $db->query("SELECT * FROM users"); echo '<h1>User Report</h1>'; while ($row = $result->fetchArray()) { echo '<p>Name: ' . $row['name'] . ', Age: ' . $row['age'] . '</p>'; } ?>
This code generates an HTML report containing all users' names and ages.
<?php $db = new SQLite3('data.db'); $result = $db->query("SELECT * FROM users"); $filename = 'report.txt'; $file = fopen($filename, 'w'); fwrite($file, "User Report\n"); while ($row = $result->fetchArray()) { fwrite($file, "Name: " . $row['name'] . ", Age: " . $row['age'] . "\n"); } fclose($file); ?>
This code will create a text file called report.txt containing all users' names and ages.
Through the code examples provided, you’ve learned how to implement data statistics and report generation with PHP and SQLite. This provides a simple yet powerful tool for managing and presenting data in web development. We hope this article helps you better understand the use of PHP and SQLite together and enhances your development efficiency.