When programming, use the right tools for the job. Use tools you’re not only comfortable with but also help you get work done in a more efficient way.

I highly recommend a solid code-writing program. Whether it’s TextWrangler, BBEdit, Notepad++, Coda, Eclipse or something else, find a tool you like and use it. It should support the ability to use your cursor to select chunks of code, syntax highlighting, be able to properly handle tabs and not make them into spaces, the ability to SSH onto remote servers and work directly with code stored there and have multiple windows or tabs open at once. Features beyond that are entirely up to your personal taste.

You should have some kind of SSH command-line tool. Mac OS comes with Terminal but I prefer iTerm myself. All flavors of linux have a terminal built in as the very core. Windows? Not sure, I don’t do any programming there.

A FTP / SFTP browser is helpful but not all that necessary for most plain-jane programming work.

Why use these good tools? Does a carpenter use a pipe wrench to put in nails? No, duh. By the same token, would he use a hammer made from wood? No. Modern tools help us be more efficient and focus more time on what we’re trying to work on rather than the how of how we’re going to work on it.

August 12th, 2013

Posted In: How to Work

Leave a Comment

Sometimes you need to delete X number of records out of mysql table where the table may contain millions of records and/or gigs of data.

You could just write some code like this:

DELETE FROM screen_sizes WHERE url LIKE '%system_monitor.php%';

and call it a day.

But what happens when your query has been running for 30 seconds, shows no signs of stopping, and users page-loads are getting hung up because your MySQL server is backed up? What happens when it’s 10 minutes later and everything is still waiting on that query?

(Side note: If your table is MyISAM, a delete query blocks the table from further inserts and updates until the query is done. If you table is InnoDB, the table is not blocked but it does slow down to the point where you might have a cascade of inserts that never finish until the delete is done anyways.)

So how do you avoid this situation? Delete the records individually. This will make each query run very quickly and will put minimal load on the server. Write a little script that can be run every minute or so for as long as is needed. I’m also going to introduce a few functions in this code that will be explained in later posts, but you should still understand the concepts as-is for now.

<?php

include '../php_config/common.inc.php';

$query = "SELECT id FROM screen_sizes
			WHERE url LIKE '%system_monitor.php%'
			LIMIT 100";
$ids = getMySQLValues($query);
if($ids) {
	foreach($ids AS $id) {
		$screenObj = new screen_size($id);
		$screenObj->delete();
	}
}

?>

Putting a limit on the query as shown above helps the results come back quickly and limits the number of records you’re dealing with at any given time.

If you have 10,000 records you want to delete and you’ve setup the above script to run once a minute via cron job, it’ll take 1 hour and 40 minutes to complete the deletion procedure. Is that a lot longer than just running a delete query? Sure. Does it keep your system happy and keep users from ever knowing anything was going on? Yep.

In this example, we’re working with a very small set of records in a simple table but the same idea applies and is more relevant when trying to delete millions of records from a complex table with billions of records and dozens of indexed fields. In those cases, there’s no other way to keep a system responsive and still perform the operations you want in real-time without taking the whole system down for “maintenance”.

August 12th, 2013

Posted In: Systems

Leave a Comment

I believe in having controllers that are straightforward and relatively simple. Decoding the logic of your controller should be an oxymoron. There’s very few times that a controller needs to have very sophisticated logic.

In the example below I’m going to show how based on user inputs the system will decide what steps need to be taken by the user and how it all works very cleanly within the command structure. This is a rather simple example but hopefully you can see how it could be modified for far more complex situations. I’m also keeping the forms and structures overly-simple for demonstration purposes. I’m also assuming that I’m using a pretty simple object.

You will see in this and other examples that I often mix my views and controllers in one file. This is not an issue so long as you’re using the command structure so it’s obvious which bits and pieces are views and which are controllers. When you loose that distinction is when you really get in trouble with messy code.

<?php

include 'header.php';

$command = $_REQUEST['command'];
if($command=='') {
	$command = 'pre-eval';
}

$myObj = new my_object($_REQUEST['id_my_object']);

// This is a very basic controller that figures out where to start (or end)
if($command=='pre-eval') {
	if($myObj->getFeeling()!='' && $myObj->getProgramming()!='') {
		header("Location: ".$_SERVER['PHP_SELF']."?command=thank&id_my_object=".$myObj->id);
		exit;
	} else {
		header("Location: ".$_SERVER['PHP_SELF']."?command=step1&id_my_object=".$myObj->id);
		exit;
	}
}
		
// This is essentially a "view" that presents a form
if($command=='step1') {
	?>
		<form action="<?=$_SERVER['PHP_SELF']?>" method='post'>
			<input type='hidden' name='command' value='step1_save'>
			<input type='hidden' name='id_my_object' value="<?=$myObj->id?>">
			How are you feeling today?
			<select name='feeling'>
				<option value="">Please Select</option>
				<option value="Great">Great</option>
				<option value="OK">OK</option>
				<option value="Awful">Awful</option>
				<option value="Unsure">I dunno</option>
			</select>
			<br>
			<label>
				<input type='checkbox' name='doStep2' value='true'> I want to answer more questions
			</label>
			<br>
			<input type='submit' value='Continue'>
		</form>
	<?
}


if($command=='step1_save') {
	$myObj->setFeeling($_REQUEST['feeling']);
	$myObj->Save();
	if($_REQUEST['doStep2']=='true') {
		header("Location: ".$_SERVER['PHP_SELF']."?command=step2&id_my_object=".$myObj->id);
		exit;
	} else {
		header("Location: ".$_SERVER['PHP_SELF']."?command=thank&id_my_object=".$myObj->id);
		exit;
	}
}

if($command=='step2') {
	?>
		<form action="<?=$_SERVER['PHP_SELF']?>" method='post'>
			<input type='hidden' name='command' value='step2_save'>
			<input type='hidden' name='id_my_object' value="<?=$myObj->id?>">
			Do you like programming?
			<select name='like_programming'>
				<option value="">Please Select</option>
				<option value="Yes">Yes</option>
				<option value="No">No</option>
				<option value="Unsure">I dunno</option>
			</select>
			<br>
			<input type='submit' value='Continue'>
		</form>
	<?
}

if($command=='step2_save') {
	$myObj->setProgramming($_REQUEST['like_programming']);
	$myObj->Save();
	header("Location: ".$_SERVER['PHP_SELF']."?command=thank&id_my_object=".$myObj->id);
	exit;
}

if($command=='thank') {
	?>
		Thank you for completing the questions.  You said:<br>
		Feeling: <?=$myObj->getFeeling()?>
		<? if($myObj->getProgramming()!='') {
			<br>
			Programming: <?=$myObj->getProgramming()?>
		}
		
	<?
}

?>

August 12th, 2013

Posted In: Controllers

Leave a Comment

I’m a fanatic about using tabs properly in code. It can make the difference between easily-readable code and a nightmare.

Of the two code segments below, which would you rather work with?

$out .= selectList(array('name'=>'type',
'id'=>'typeSelection',
'elements'=>array('Unspecified'=>'- please select -',
'questions'=>'General Questions',
'quote'=>'Request Info/Demo/Quote',
'order'=>'Place Order',
'comment'=>'Feedback/Comment'),
));
$out .= selectList(
			array(
				'name'=>'type',
				'id'=>'typeSelection',
				'elements'=>array(
							'Unspecified'	=> '- please select -',
							'questions'		=> 'General Questions',
							'quote'			=> 'Request Info/Demo/Quote',
							'order'			=> 'Place Order',
							'comment'		=> 'Feedback/Comment'),
				));

August 7th, 2013

Posted In: Syntax

Leave a Comment

I have a very specific way I like to create my objects which seems to work very well.  I’ve ben using it for years now and it consistently does what I want my object to do: hold the logic of the object and allow me flexibility in the future for upgrades to ideas on how the object should work.

My objects are generally centered around the idea of a row in a MySQL database.  A job for instance would be one row in a database a a job object would represent that data plus all of the code necessary to make it function in the system I’m working on.

I generally make getVariable and setVariable type functions for each column in the database.  Technically yes, this is overkill, until your boss one day decides to append ad additional function when the value changes from X to Y on a certain column and your system now needs to do additional work on that concept.

Yes, there are more efficient methods of getting and setting data into databases, but I stand by this one and I believe it’s a highly re-usable concept that has served me extremely well over the years.

You’ll notice some functions in this object that are not well (or at all) defined here.  I’ll follow up with more posts in the future describing what they are, why they are, what they do, and some example code for each. You’ll also see that I reference a field called “id”. In all of my tables I always create an id field that is the primary key that auto-increments. Does this use more space? Yes. Does it make life a metric ton easier? Yes.

<?php

class job {
	var $id;
	var $data = array();
	var $tableName = "jobs";
	var $databaseName = "my_database_name";

	function __construct($params=array()) {
		if(!is_array($params)){
			$params = array('id'=>$params);
		}
		if(@$params['id'] > 0){
			$query = 'SELECT * FROM 
						`'.$this->databaseName.'`.`'.$this->tableName.'` 
						WHERE `id` = "'.encodeSQL($params['id']).'" 
						LIMIT 1';
		}
		if($query != NULL){
			$result = getMySQLData($query);
			if(mysql_num_rows($result) > 0){
				$this->data = @mysql_fetch_assoc($result);
				$this->id = $this->data['id'];
			}
		}
	}


	function getTitle() {
		return $this->data["title"];
	}

	function getIDhiringManager() {
		return $this->data["id_hiring_manager"];
	}
	
	function setTitle($input) {
		$this->data["title"] = $input;
	}

	function setIDhiringManager($input) {
		$this->data["id_hiring_manager"] = $input;
	}

	function dataChecks() {
	}
	
	function save() {
		$this->dataChecks();
		$this->id = objectSave(	$this->tableName, 
								$this->id, 
								$this->data, 
								$this->databaseName, 
								array('writeAudit'=>true)
								);
	}
	
	function duplicate() {
		$this->id = NULL;
		$this->data['id'] = NULL;
	}
	
	function delete() {
		objectDelete(	$this->tableName, 
						$this->id, 
						$this->databaseName, 
						array('writeAudit'=>true)
					);
	}
	
}

July 26th, 2013

Posted In: Objects

Leave a Comment

Focus is incredibly important.  In the last several months I found myself distracted with switching back and forth between so many projects that I wasn’t effectively getting anything done which resulted in even more open or pending projects.  It also made me feel like I was a ball in the pinball machine, never knowing which way I was going to be thrust.

I’ve redesigned my week so that I have periods of dedicated programming time that cannot be interrupted by anything short of an emergency.  Technically, this is only about 2 hours per day but it’s resulted in a whole ton of stuff actually getting done, and that’s fantastic.  Accomplishing projects that were somewhere in the medium-difficulty range that simply weren’t being done before is fantastic to have that sense of accomplishment again.

If you’re finding yourself so busy you can’t seem to get anything done, then block off some time and do only one thing.  Everything else can wait, because it would be waiting anyways.

July 19th, 2013

Posted In: How to Work

Leave a Comment

One of my favorite tricks lately is storing an array of data in a serialized format and writing it to a database.  This is really handy when you have an arbitrary set of information that needs to be stored that doesn’t really fit anywhere else and does not need to be searchable or sortable.

An example I had recently required me to store whether or not 4 checkboxes were checked or not on a record.  I could have created 4 additional fields or a related table where it would create 4 additional records per original object, or I could just store this as an array and serialize it and be done with it.  Since I already had a “generic_data” table, I just added this to that table and in a couple minutes I was done.  Awesome.

How does it work?  Well, something like this (showing ideas here, not full code chunks):

if($command=='view') {
	$raw = $obj->getSerializedData(); // read data from the database
	if($raw!='') {
		$myArray = unserialize($raw);
	}
	if(!is_array($myArray)) {
		$myArray = array();
	}
	// do whatever display is needed with $myArray
}
if($command=='save') {
	$myArray = $_REQUEST['x']; // assuming $_REQUEST['x'] is an array
	$obj->setSerializedData(serialize($myArray)); // write to the database
	$obj->Save();
}

June 7th, 2013

Posted In: Shortcuts, Syntax

Leave a Comment

Don’t be vague in your communications and assume that people know what you’re talking about.  All you’re going to do is spawn more communications and delays.  Take an extra couple seconds and include the right words, images, or just general clarity so the receiver knows what you’re talking about.

May 23rd, 2013

Posted In: How to Work, HR

Leave a Comment

ta-why-internet-explorer-must-die-0

May 17th, 2013

Posted In: Uncategorized

Leave a Comment

I write “report” pages all the time. These pages usually consist of some kind of filterable elements at the top with the results below. When the user fills out a filter element such as “status”, they expect that value to be retained when the page refreshes. And if he/she is going to proceed to the second “page” of results, that filter should still remain in place.

Pasted below is little code that helps maintain “sticky” filters, swap out bits and pieces as necessary for your reporting. This is obviously a really simple example that doesn’t have a lot of the UI elegance you’d put into a real report, but I think the point is made that storing the filtered elements into a session array is the easiest way to make them “stick” between page loads.

<?
$sesParams = &$_SESSION['session_reportName'];
if(!is_array($sesParams)) {
	$sesParams = array();
}
if(isset($_REQUEST['newParams']) || isset($_REQUEST['clear'])) {
	$sesParams = array();
	$fieldsToGet = array(	'date_from',
				'date_to',
				'status',
				);
	foreach($fieldsToGet AS $fieldName) {
		$sesParams[$fieldName] = $_REQUEST[$fieldName];
	}
}
?>
...

<form action="<?=$_SERVER['PHP_SELF']?>" method='post'>
	<input type='hidden' name='newParams' value='true'>
	<table class='body10'>
		<tr>
			<td>
				From: 
				<input type='text' name='date_from' value="<?=$sesParams['date_from']?>">
			</td>
			<td>
				To:
				<input type='text' name='date_to' value="<?=$sesParams['date_to']?>">
			</td>
			<td>
				Status:
				<input type='text' name='status' value="<?=$sesParams['status']?>">
			</td>
			<td>
				<input type='submit' value='Filter' class='input10'>
				<input type='button' value='Clear' class='input10' onclick="window.location='<?=$_SERVER['PHP_SELF']?>?clear'">
			</td>
		</tr>
	</table>
</form>

May 3rd, 2013

Posted In: Shortcuts, User Interface

Leave a Comment

« Previous PageNext Page »