Hidden Frame Pattern / Pre-Ajax

This is one of the knows patterns in the web devs. The idea would be having two – or possibly more – frames and making one the front one for interaction while would be HIDDEN.
Why Hidden?
The visible frame would pass make a request to the hidden frame to make the server side interaction behalf of it. Doing so would make the visible frame to remain loaded. The hidden would play the rest of the game by consulting the server and grabbing all the required data. Of course, how do they talk? well, Mr. Javascript will be the ‘man in the middle’ – don’t wanna mention the security flaw known by this name 😉

Let’s see a quick example: the example will show how to interact with the server side script without page reload. For demo purpose, A page will accept first name and last name and will display the concatenated full name. Though the logic done is is too easy to accomplish, one has to bear in mind that any complex logic can be done in the same way.

First create a simple index file containing the frames

		<frameset rows="100%, 0" style="border: 0px">
			<frame name="visibleframe" src="enterName.html" noresize="noresize"></frame>
			<frame name="hiddenframe" src="about:blank" noresize="noresize"></frame>

Making the frameset row 100% will assure the full visibility.
Then have the page for first and last name.

	//get full name by delegating the task to the php 
	function getFullName(){
		var firstName = document.getElementById("txtFirstName").value;
		var lastName = document.getElementById("txtLastName").value;
		top.frames["hiddenframe"].location = "concateName.php?firstName="+firstName+"&lastName="+lastName;
	//display it on the front page 
	function showFullName(fullName){
		showdiv = document.getElementById("fullName");
		showdiv.innerHTML = fullName;
Your First Name <input type="text" id = "txtFirstName" name="txtFirstName" /> <br>
YOur Last Name<input type="text" id="txtLastName" name="txtLastName" /> <br>

<input type="submit" name="subGetFullName" value = "concate" onClick="getFullName();" /> <br>
<textArea id="fullName" name="fullName"></textArea>

This file contains two javascripts: one for sending the form values to the hidden frame and the other to accept and display the result from the hidden frame.
Since the hidden frame had no source initially, the getFullName() function would be responsible for assigning the file to it.

Now lets build the server side script which will combine and return the full name

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    window.onload = function(){
       var fullNameDiv = document.getElementById("fullName");
        $firstName = $_GET['firstName'];
        $lastName = $_GET['lastName'];
        $fullName = $firstName . $lastName;
        <body><div id="fullName"><?php echo "FULL name is " . $fullName ?>

Now we are done. :)
The concateName.php would get the parameters from the enterName.html through hiddenframe. Once it access the values, it will concatenate them and will deploy the result in the “fullName” div.
The defined window.onload would wait until things are in place and it will fire the result back to the “visibleframe” through javascript.
Now – the user has no what is going on behind he scene – as she will not see the page being reloaded on refreshed.

reference: Professional Ajax 2nd edition Wrox

403 Forbidden You don’t have permission to access .. on windows pc

You don’t have permission to access error

I was trying to access my PHP web project from my Vista on my Ubunut and end up running error 403 Forbidden You don’t have permission to access on this server …

Do you know how to find missing numbers from billing records – algorithm

Well this has a very easy remedy:

BTW – I am using Uniserver – http://www.uniformserver.com/ – [ Which is the coolest development environment on windows as you would get PHP, MySQL, and PhpMyAdmin residing all at one place.]

But it doesn’t matter if you are using other tool.

1. Go to where your www folder

2. open .htaccess file using your favorite text editor – note pad is more than enough for this.

3. Under Allow From – or whatever it is allowed Add Allow From [your ip address of the computer from which you want to access the server]

Get started with nodejs and angularJS with this tutorial

How to configure php mysql and apache

Can’t use method return value in write context – php Error

Yup, just to share – as usual.
While working on one of my projects I run this error. Here is the snippet where the error occurs:

        $carPrice = $this->getCarPrice(); // this would return object of CarPrice
        if (empty($carPrice->getCarPriceId()))

Where $carPrice is an object to be returned after passing an array of data ($new_price) to the controller.
And on the next line, I was trying to if priceId of the car is not empty.
The problem is caused on the second operand of the if statement (empty($carPrice->getCarPriceId()) –
Here is how I get fool around..

$car_price_id = $carPrice->getCarPriceId();
if (empty($car_price_id))

It happens that function empty() [and even isset() ] do expect a variable to be checked otherwise, parse error will happen.

Encapsulating Queries in Object

Here is some more pattern for you. I have provided how to implement singleton pattern for database.
The idea is:
Why don’t we encapsulate our queries to the database in an object?
What we need is to execute a query whether it is update query – like delete, update and insert or retrieval query like select. In both cases, the the accomplishment would be one – executing – with different query parameters.
Which means we need only a single interface per application for that would simply execute our queries independent of the query string.
The encapsulating class for queries (acting as command) shall contain the implementation of method executeQuery().

Query class: implementing the basic tasks of query
Author: Kaleb B. Woldearegay
Date: 18.Apr.2009

Open for any kind of modification and use.
Please let me know when you use and modify it as I will learn from that 
	class Query{
		protected $sql;
		protected $db; /*any database implementing IDatabase */
		/*Method executeQuery would accept query string 
and executes it using the database's execute query method */
		public function __construct($database){
			$this->db = $database;
		protected function executeQuery($sql){
			return $this->db->executeQuery($sql);

Another point here would be, since we have two major tasks to perform against database – namely update queries and retrieval queries – we need two query commands which would be the derived classes of Query class

	/* This class would perform non resulted queries - 
like update, insert and delete
-- Query.php--
	class UpdateQuery extends Query{
		/* constructor would pass the database for query class */
		public function __construct($db){
		/* execution of queries would goes here */
		public function executeQuery($sql){
			return parent::executeQuery($sql);		

	/* This class would perform resulted queries - like select */
	class ResultQuery extends Query{
		/* constructor would pass the database for query class */
		private $result; /* result object that would be created from database */
		public function __construct($db){
		/* constructor would pass the database for query class */
		public function executeQuery($sql){
                        /* Assigning the object */
			$this->result =  parent::executeQuery($sql); 
			return $this; //return the result query;
		/* Collect the row from the collected result */
		public function getRow(){
			/*using associative array for the rows*/
		       if ( $row=mysql_fetch_array($this->result,MYSQL_ASSOC) ) {

            			return $row;

        		} else if ( $this->size() > 0 ) {


            			return false;

        		} else {

            			return false;


		/* Size of the collected result */
    		public function size () {

        		return mysql_num_rows($this->result);


The hot-to-go part is simple. Any query should be executed! But the type of query is different – some require result set and other don’t. Which is a kind of topping we want on our query pizza. UpdateQuery and ResultQuery would provide the different type of flavors.
So, the client would encapsulate its request in either of the commands and would call an execute method.
But, this has some problem. We would need to know specifically of which type the query is. But what if we have an interface which would accept any command object and invoke its execute method – this seems neat..

Query class: implementing the basic tasks of query
Author: Kaleb B. Woldearegay
Date: 18.Apr.2009

An invoker class would implement the 'command' pattern over 
the database applicaion
the invoker would be called by any client who needs a service 
from database either update or non-update

	class QueryInvoker{
		private $query_obj; /*any query object inheriting 
from Query class */
		public function __construct($query_obj){

		public function setQuery($query_obj){
		/*the invoker would accept object [ which could be 
either update query object or non update query object ] which it 
has no any idea, and would invoke its  execute method */
		public function execute($query_obj,$sql){
			return $query_obj->executeQuery($sql);

An example showing the interaction would be:

/*this example assumes you would put all your classes in the 
folder named classes - which is a practice of course.
	$obj_invoker=new QueryInvoker();
	$objUpdate=new ResultQuery($objDb);
	$sql="select * from tbl";
	$result = $obj_invoker->execute($objUpdate,$sql);
        while($row = $result->getRow()){do stuff}

You can get Mysql class in the singleton pattern part of my article.

Singleton in PHP

One of the commonly utilized part in programming is database access. Accessing a database in PHP is by far tied with his beloved one: MySQL.

While connecting and working with database, we have to limit the number of connections to database. Especially in a single database environment, the program shall utilize one object efficiently for all of its actions. Resource management and efficiency would be increased in doing so.

I have tried to apply the singleton pattern on the database class and share it here.
I have an interface with the following signature:

/* An interface for database.  
Author: http://gullele.com
Open for any modification and usage
Date: 18.Apr.2009
	interface IDatabase{
		/* method for connection */
		public function connect();
		/* method for opening the database */
		public function open();
		/* method for closing */
		public function close();
		/* method for query that returns result - common for other kind of databases like SQL Server */
		public function executeQuery($query);
		/* method for query that does not return result */	
		public function executeNonQuery($query);
		public static function getInstance(); /*function to return a static instance of a class*/

This interface would assure all the implementers would have the same functions all over.
If we have this, later, if we change the database – those methods who have been using the database class would remain unaffected.

Here is the mysql database which implements the interface and the logic of singleton pattern is applied.

Author: http://gullele.com
Open for modification and any use - please let me know when you use/modify it as I might learn from your modification. 
Date: 18.Apr.2009
class Mysql implements IDatabase{
		private $host; 
		private $username;
		private $password;
		private $db_name;
                private $connection_error;
		private static $instance = null; /*an instance of the class*/
		/* Connection object to be assigned for the database selected */
		private $connection; 
		/* Make the constructor private or protected to prevent the object from being instantiated directly - this is how to make it singleton pattern being applied*/
		private function __construct(){
			$this->host = 'localhost';		
			$this->username = 'root';
			$this->password = 'root';
			$this->db_name = 'intramicro';
		/* Connecting to the database it also opens the database */
		public function connect(){

        		if (!$this->connection = @mysql_connect($this->host,

                            $this->username,$this->password)) {
	    			echo "Connection error";

            			trigger_error('Error Connection to database');


        		/* Assing to the database for initial use - can be changed later if needed */

        		} else if ( !@mysql_select_db($this->db_name,$this->connection) ) {

            		trigger_error('Database selection error');


		/* Implementation is not needed for this method as mysql would open the database when it connects to it */
		public function open(){
		/* Closing the database - used for non-persistent connection*/
		public function close(){
		/* A method to accept query object, execute it and return resource object */
		public function executeQuery($query){
			if (!$query_resource=mysql_query($query,$this->connection))

            			trigger_error ('Query failed: '.mysql_error($this->connection).' SQL: '.$query);	
			return $query_resource;
		/* Non query method is not needed in the MySQL database as it can be done with my_sql()*/
		public function executeNonQuery($query){}
		public static function getInstance(){
				self::$instance=new self();
			return self::$instance;

It is necessary to make the constructor of the implementing class private or protected to inhibit the direct instantiation of the object from the clients.
The clients shall know enjoying the object of MySQL class would only through the static getInstance() method of the class.

Here is an example

require(‘…MySQL.Database.php’); //include the file here
$objDb=Mysql::getInstance(); //get instance here
Once it is instantiated, a single object would serve for many clients.
You may want to check the security, error handling and some additional things by your own.
Cool.. Continue reading Singleton in PHP