:::: MENU ::::

Demo: PHP-MySQL database connection using namespaces

Namespace in PHP:-

Namespace concept isn’t any new for programmers coming from c++, java, python or ruby platform.  They are a way of encapsulating classes. You could compare it with package in other programming language, which contains several classes.

Advantages of PHP Namespaces:-

  1. Prevents class collisions of different libraries.
  2. Allow to use class alias to make code more readable.

Defining and importing Namespaces in PHP.

They can be separated by forward slashes.

Now to use it,

Example:- code readability with namespaces

See the database table structure for above code.

Using namespace in PHP code

We’ll have following file structure to arrange the namespace.


Make config file with global configuration:-

  • Above code makes default setting for database connection.
  • we made __autoload() function to specify php how it should load class files.
  • In our example  __autoload() function looks into directory “import”.
  • Then every namespace would be store as separate directory.
  • classes within that namespace will be stored inside namespace  directory.

Example, see following code

___autoload() will look for file into following location.

Revisiting basic mysql functions

Function NameDescription
mysql_connect(‘HOSTNAME’,’USER’,’PASSWORD’);Connects to mysql server.
mysql_select_db(‘DATABASE’);Select database from mysql
mysql_query(‘SQL’)Does SQL manipulations
mysql_fetch_row / mysql_fetch_array / mysql_fetch_assocGets SQL results into array.
mysql_close()Closes Database Connection

Create mysql class into DB package

Create query class into MySQL package

Creating demo.php file

You could download sample working code here. In upcoming post I’ll explain how to plug mysqli class to this DB package without changing core business logic.

One Comment

So, what do you think ?