• Posted on April 14, 2014

Easy PHP Scheduled Content

A lot of sites have some sort of scheduled / delayed content system to help stockpile posts so you don’t need to work every day or at the very least have to manually submit the posts when you want to. I’ve seen sites use cron jobs to handle this feature but the easiest way is to use your existing date column for the content.

With most content tables, you will have a published date column so the user can see when the content was written or submitted. Use this column to your advantage for scheduled posting. Using the simple database setup below, we will create scheduled posts.

CREATE TABLE `posts` (
	`id` INT UNSIGNED AUTO_INCREMENT,
	`title` VARCHAR(100) NOT NULL,
	`date` INT UNSIGNED DEFAULT 0,
	`content` TEXT NOT NULL,
	PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT;

If we use the above table to store our posts, the PHP code to interact with it will look similar to the following. This uses the PDO Database class for PHP which is now recommended. I didn’t setup the construct for PDO with the correct value parameters so you will have to set these values yourself.

$dbh = new PDO($dsn,$username,$password);
$query = "SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 5;";
$sth = $dbh->prepare($query);
if(!$sth->execute()) {
	trigger_error('Error Loading Posts',E_USER_ERROR);
	die();
}
$posts = $sth->fetchAll(PDO::FETCH_ASSOC);

But with one simple change to the above code, we can create scheduled posts.

$dbh = new PDO($dsn,$username,$password);

$query = "SELECT * FROM `posts` WHERE `date` <= ? ORDER BY `date` DESC LIMIT 5;";
$data = array(time());

$sth = $dbh->prepare($query);
if(!$sth->execute($data)) {
	trigger_error('Error Loading Posts',E_USER_ERROR);
	die();
}
$posts = $sth->fetchAll(PDO::FETCH_ASSOC);

The changes above were located inside of the $query variable, along with creating a $data variable and also inserting the $data variable inside of the $sth->execute() function.

The reason this works is simple, we only request posts that are from the past and not the future. When you insert data into your database, use the mktime() function for the future date you wish to have the post published.