Some time ago I wrote myself a simple blog. The index page is generated
with PHP5, using an SQLite3 database via the variable id handed to it via
the URL.
The SQLite database contains a table called pages. The id refers of course
to the id intergers in this table. Other columns are title, body, time and
timezone.
The title and body are text as you'd expect, the timezone is usually
"Asia/Tokyo", and the time is seconds from the epoch (I just use date +%s,
when I add an entry, nothing fancy).
I use the following code to get these variables from a table, and fill in a generic page with them.
<?php
// Open the database.
$db = new PDO("sqlite:pagesdatabase.db");
// Is id set? If not get id of last page and put it in $id.
if (!isset($_GET["id"])) {
foreach ($db->query("select max(id) from pages") as $lastid) {
$id = $lastid[0];
}
}
// If id is set, get the value and put it in $id.
else {
$id = $_GET['id'];
}
// Using the id number, grab the title, body, time and timezone of post.
foreach ($db->query("select * from pages where id = $id") as $page) {
$title = $page['title'];
$body = $page['body'];
$time = $page['time'];
date_default_timezone_set($page['timezone']);
}
?>
This code works, but seems rather clumsy to me. For example, foreach
appears twice, but shouldn't be necessary. To be honest, it's been a while
since I wrote this code, and for some reason I had trouble using sqlite_open
and other more obvious functions. Can someone help me write the above in a more
terse way?
foreachshould not be necessary. As for your last two comments, it doesn't matter since there's only one element. \$\endgroup\$