PHP and SQLite Starter Project
Build a reading list you can run locally. Add a book, mark it as read, and restart the server to see that it is still there. The app uses a single PHP file and a SQLite database that it creates on your machine.
What you need
Section titled “What you need”Use PHP 8.6 or later with PDO SQLite. Check that PHP can see the driver:
php -vphp -r 'print_r(PDO::getAvailableDrivers());'Look for sqlite in the list. The troubleshooting guide covers missing drivers.
Download and run
Section titled “Download and run”Save the starter PHP file as php-sqlite-starter/public/index.php, or use the commands below.
macOS or Linux
Section titled “macOS or Linux”mkdir -p php-sqlite-starter/publiccurl -fL https://raw.githubusercontent.com/dalehurley/codewithphp/main/code/php-sqlite-starter/public/index.php \ -o php-sqlite-starter/public/index.phpcd php-sqlite-starterphp -S 127.0.0.1:8000 -t publicWindows PowerShell
Section titled “Windows PowerShell”New-Item -ItemType Directory -Force -Path 'php-sqlite-starter/public'Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/dalehurley/codewithphp/main/code/php-sqlite-starter/public/index.php' -OutFile 'php-sqlite-starter/public/index.php'Set-Location 'php-sqlite-starter'php -S 127.0.0.1:8000 -t publicOpen the reading list at localhost and add a book. PHP creates the SQLite file on the first request.
php-sqlite-starter/├── public/│ └── index.php└── storage/ └── reading-list.sqliteThe -t public option makes public/ the document root. The database stays in storage/, outside the directory the server serves. Use this development server on your own machine. PHP development server
Follow one book through the code
Section titled “Follow one book through the code”- Open the page. A GET request opens the SQLite file and runs a SELECT to show the saved books.
- Add a title. The form sends a POST with a session token. PHP checks the token and title, then passes the title to an INSERT as a prepared-statement parameter.
- Read the result. PHP sends a redirect back to the list. Refreshing that page repeats the GET and keeps your new book from being submitted again.
- Mark the book as read. The second form sends the book ID. An UPDATE saves its status. Stop the server with Ctrl+C, start it again, and open the list to check that both changes persisted.
Titles are escaped when PHP renders them. Try a title containing & or quotes and check that it appears as typed.
Use the starter in a lesson
Section titled “Use the starter in a lesson”- Trace the requests in your browser to see the POST, redirect, and follow-up GET.
- Teach the app in 45 minutes with a timed plan, exercises, and solutions.
- Check your finished reading list before extending the app.
When the starter is working, try adding an author field to the form and database. The PDO lesson explains the SQL calls, and the sessions and cookies lesson shows where the form token is stored. Browse the starter source