Categories
Development

PHP Advent 2009

I had no idea something like this existed but what a great idea. 24 days of worth of PHP articles to keep the Christmas Blues away.

Today’s article is something very close to my heart and discusses the topic of Comprehensible Code.

Go, read, expand your minds….

Categories
Development

Migrating from Drupal to WordPress

Well, it finally happened. After months of frustration with Drupal as a blog tool, I gave up and decided it was time to move over to WordPress.

I’m sure as a CMS system Drupal can be quite wonderful, but for running and managing a simple blog site, I have yet to come across a better platform than WordPress.

However the migration of the database content from one system to another had it’s ups and downs. Fortunately for me, not many people read this blog, so I only had to migrate the posts data from one database to the other.

Below is the script I wrote to do so, in the hopes that this might save someone else the hassle of writing it themselves.

P.S. This was for a Drupal 6 to WordPress 2.8.2 migration. If it doesn’t work for you because you are working with different versions of either Drupal or WordPress, drop me a line and I will try to modify it for you.


	/**
	* Setup database constants
	*/
	define('DRUPAL', 'phpdevec_drpl1');
	define('WORDPRESS', 'phpdevec_wordpress');
	define('URL', 'http://www.php-developer.co.za/');
	/**
	* Setup server constants
	*/
	define("SERVER", "localhost");
	define('USER', 'username');
	define('PASSWORD', 'password');

	/**
	* debug function outputs data
	*/
	function debug($data){
		echo '<pre>';
		print_r($data);
		echo '</pre>';
	}

	/**
	* Connect to server and database
	*/
	function connect($db) {
		// database connection
		$conn = mysql_connect(SERVER, USER, PASSWORD);
		if (!$conn) {
			//connection to server failed
			die("Cannot connect to server");
			return false;
		}

		$dbSelected = mysql_select_db($db, $conn);
		if(!$dbSelected) {
			// database connection failed
			die("Cannot connect to database");
			return false;
		}
		return $conn;
	}

	/**
	* Close database connection
	*/
	function disconnect($conn){
		if ($conn){
			// connection exists to close
			if (!mysql_close($conn)){
				// database connection failed
				die("Cannot close database connection");
				return false;
			}
			return true;
		}
		// default return in case the original connection failed
		return true;
	}

	/**
	* Generic SQL SELECT, checks type
	* (SELECT, INSERT, UPDATE [DELETE])
	*
	* @param string $sql query
	* @param string $type object or assoc
	* @return mixed $return array of rows if select or true/false if insert/update/delete
	*/

	function sql($sql, $database, $type = 'assoc'){
		$return = '';

		// check database connection
		$connection = connect($database);
		if (!$connection){
			$return = false;
		}

		$sql = ltrim($sql);
		$query_type = substr($sql, 0, 6);

		// run query
		$rst = mysql_query($sql);

		if (!$rst){
			// query failed for some reason
			die("Error in MySQL query: " . $sql);
			$return = false;
		}else {

			if (strtoupper($query_type) == "SELECT"){
				// query was SELECT
				$return = array();
				$rows = mysql_num_rows($rst);

				switch($type) {
					case 'assoc' : // return as assoc array
						while($row = mysql_fetch_array($rst)) {
							// gather rows
							$return[] = $row;
						}
						break;
					default : //return as object
					while($row = mysql_fetch_object($rst)) {
						// gather rows
						$return[] = $row;
					}
				}
			}else {
				// query was INSERT, UPDATE OR DELETE
				$queryType = 'UPDATE';
				if (mysql_insert_id()){
					// query was INSERT
					$id = mysql_insert_id();
					$queryType = 'INSERT';
					$return = $id;
				}else {
					$rows = mysql_affected_rows();
					$return = $rows;
				}
			}
		}

		// disconnect from database
		disconnect($connection);

		//return rows / whether insert/update/delete successful
		return $return;
	}

	$sql = "SELECT n.*, nv.body as content FROM node as n LEFT JOIN node_revisions as nv on n.nid = nv.nid WHERE n.type = 'blog'";

	$nodes = sql($sql, DRUPAL);

	//debug($nodes);

	$Nodes = array();

	foreach ($nodes as $node){
		$nId = $node['nid'];
		$sql = "SELECT * FROM comments WHERE nid = '$nId'";
		$comments = sql($sql, DRUPAL);
		$node['comments'] = $comments;
		$Nodes[] = $node;
	}

	//debug($Nodes);

	foreach ($Nodes as $node){
		//publish draft

		$two_hours = 2*3600;
		$date = $node['created'];
		$gmt_date = $date - $two_hours;
		$modified = $node['changed'];
		$gmt_modified = $modified - $two_hours;

		$post_date = date('Y-m-d H:i:s', $date);
		$post_date_gmt = date('Y-m-d H:i:s', $gmt_date);
		$post_modified = date('Y-m-d H:i:s', $modified);
		$post_modified_gmt = date('Y-m-d H:i:s', $gmt_modified);

		$post_title = mysql_escape_string($node['title']);
		$post_content = mysql_escape_string($node['content']);
		$post_name = strtolower(str_replace(array(' ', '.'), array('-', ''), $post_title));

		$status = $node['status'] == '1' ? 'publish' : 'draft';

		$sql = "INSERT INTO phpdevec_posts SET
			post_author = 1,
			post_date = '$post_date',
			post_date_gmt = '$post_date_gmt',
			post_content = '$post_content',
			post_title = '$post_title',
			post_status = '$status',
			comment_status = 'open',
			ping_status = 'open',
			post_name = '$post_name',
			post_modified = '$post_modified',
			post_modified_gmt = '$post_modified_gmt',
			post_parent = '0',
			menu_order = '0',
			post_type = 'post',
			comment_count = 0";

		$id = sql($sql, WORDPRESS);

		if (!$id){
			die('An error occured adding the data to the database');

		}

		/*
		if (!empty($comments)){
			foreach ($comments as $comment){
			}
		}
		*/

		$guid = URL . "?p=$id";

		$sql = "UPDATE phpdevec_posts SET guid = '$guid' WHERE ID = '$id'";

		$updated_rows = sql($sql, WORDPRESS);

		if (!$updated_rows){
			die('An error occured updating record no '. $id);
		}
	}

Categories
Development

Create an array containing the days of the week

You could simply code:

$days_of_week = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

but thats the “noob” way, a real coder creates a function…

function days_of_week() {
	// declare days_of_week array
	$days_of_week = array();

	// get current date integer value (0 - 6)
	$day = date( "w" );

	// get current date values
	$today = date( "j" );
	$month = date( "n" );
	$year  = date( "Y" );

	// get start day and end day of the week
	$start_day = $today - $day;
	$end_day   = $start_day + 6;

	// build days of the week array
	for ( $i = $start_day; $i & lt;= $end_day; $i ++) {
		$days_of_week[] = date( "l", mktime( 0, 0, 1, $month, $i, $year ) );
	}

	// return array
	return $days_of_week;
}

Update: 13/05/2018

Sigh What was wrong with me back then, this would have been so much better.

function days_of_week(){
	return = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
}

Keep it simple, stupid!

Categories
Development

PHP.js

This is something I came across a while ago, but it has really come in handy.

It is a project that attempts to make many php functions available in javascript. As most php developers will at some point have to write some javascript, it is a very handy library.

You can find it over at http://www.ohloh.net/p/php-js.

Categories
Development

Life of a developer

It has been a while since I have posted here, mainly due to the time consuming period that is the festive season and also because I am discovering that I am getting fairly annoyed by Drupal as a blog tool and am trying out the new WordPress as an alternative.

For now I have a small post on something that many people aren’t aware of but is VERY handy, the ternary operator.

Basically it is a shortcut to do a simple if-then-else statement in one line when you are performing fairly simple checks for a single value. I tend to use it a lot when checking for GET or POST variables.

So:

$getContents = (isset($_GET) ? $_GET : array());

would check if the $_GET variable array is set, if it is return its contents to $getContents and if not return and empty array to $getContents.

Much easier that coding:

$getContents = array();
if (isset($_GET)){
$getContents = $_GET;
}

P.S. Just on a side note, if you are new to PHP and want to use this code to check for and receive your $_GET contents, dont forget to sanatize your data as well (hmm I think I see a new post topic)

Categories
Development

Last day of the month

Here’s one line of code to get the last day of a month:

$last_day = date(‘t’, mktime(0, 0, 1, $month_variable, 1, $year_variable));

How much more difficult do you want it to be ???

Categories
Development

Delving deeper into the PHP lake…testing if a variable exists in a list

As a PHP developer of almost four years now, I often still come across little problems in coding that make me do the good ol Google search to find the answer. (someday I will have memorised the entire PHP manual, but today is not that day ;-).

Anyway today I was asked about how to do a IN LIST type comparison in PHP. (similar to the mysql IN statement).

A few google searches later revealed that there exists no such PHP command, however the in_array function can be used to perform the task:

$myArray = array(1, 2, 3, 4, 5);

if (in_array($var, $myArray)){
// do some code.
}

I guess one could also combine the two as follows:

if (in_array($var, array(1, 2, 3, 4, 5))){
// do some code.
}

I’ll have to test that one, but you get the idea…

Categories
Development

Simple PHP increment function

Whenever I have to output a numbered list of data I usually run the following code to achieve the required result.

$counter = 0;
// for loop that does all the required code
$counter++;
// end for

but I have discovered a lovely little function that does all this for me.

function increment(&$counter){
$counter++;
return $counter
}

now I simply call

increment($whichever_counter)

and it automatically outputs the next numeric.

Great! Simple and easy to use…..that’s the way to code.