SQL

Saturday, 17 March 2012

Creating A Child Class

Creating a child class is pretty simple.Just create a class and use the keyword "extend" to extend the parent class.You need to make sure that thw class that you are extending is not a FINAL class because you can not extend a FINAL class.

class ChildClass extends ParentClass
{
// class definition goes here
}


The child class needs access to the file where the parent class is defined, so you need to
include the parent file before defining the child class. Since the child class depends on it,
you should normally use require_once to include the parent file.




Getter and Setter in PHP


In PHP class getter and setter methods are really useful to show the results or pull the data.When you create a value as public it is visible from everywhere.That means inside or outside the class and any one can pull the data or extend the class to change it.So here comes the private or protected privileges.set() sets the value and get() gets the value.So you can pull the data using the get().Here is a simple example:

class Employee
{
// properties defined here
protected $_name = 'John';
// methods defined here
// methods defined here
public function getName()
{
return $this->_name;
}
public function setName($name)
{
$this->_name = $name;
}

}

Now create another test.php and copy followings:
// include the class file
require_once 'Employee.php';
// create an instance of the Employee class
$employee = new Employee();
// display the $_name property
//echo "$employee->_name";
$employee->setName('Robert');
echo $employee->getName();


If you run the file you can see Robert but may be you are expecting John.This is because we have set the variable to Robert using set().

Setting default values with a constructor method

A constructor builds the object, applying default values and assigning to properties values passed to the class when an object is instantiated.
the constructor for all classes is called __construct()

The constructor works like a setter method, so any values passed to it as arguments can be
assigned to properties by using $this to refer to the current object like this:
public function __construct($value)
{
$this>property = $value;
}

Lets create a constructor with 2 properties:

// constructor
public function __construct($name, $title)
{
$this->_name = $name;
$this->_title = $title;
}

Because the value of $_name is set by the constructor, you no longer need the
setter method. So we can delete it and add a getter method to retrieve the value of the
$_title property. The Employee.php should look
like this:

class Employee
{
// properties defined here
protected $_name;
protected $_title;
// constructor
public function __construct($name, $title)
{
$this->_name = $name;
$this->_title = $title;
}
// methods defined here
public function getName()
{
return $this->_name;
}


public function getTitle()
{
return $this->_title;
}
}

the class constructor now expects two arguments. To keep the code simple, I haven’t added any code to check the type of data passed as arguments, but let’s assume that both are meant to be strings. Test the revised class by the code in test.php as follows
require_once 'employee.php';
$employee1 = new Employee('John', 'Manager');
$employee2 = new Employee('Robert', 'Cashier');
echo '$employee1 is  ' . $employee1->getName();
echo ' Title is "' . $employee1->getTitle() . '"
';
echo '$employee2 is  ' . $employee2->getName();
echo ' Title is  "' . $employee2->getTitle() . '"
';

When you run test.php, you should see something similar to



$employee1 is John Title is "Manager"
$employee2 is Robert Title is "Cashier"



Wednesday, 7 March 2012

Simple MySQL Class connection Test

This is a very simple PHP class to check MySQL connection.Please read my other blog to create the MySQL table to make things work.
define("server","localhost");
define("conn_username", "root");
define("conn_password", "root");
define("database_name", "database_1.1");


require "database.inc.php";
 
 class mysql 
 { 
     function connect() { 
      @mysql_connect(server,conn_username,conn_password); 
      @mysql_select_db(database_name); 
  } 
 
     function query($query) { 
         $result = mysql_query($query); 
         if (!$result) { 
             echo 'Could not run query: ' . mysql_error(); 
             exit; 
   } 
   else{
    return $result;
   }
     } 
     
     function showresult($result) {
      $arr = array();
    @mysql_data_seek($result);
    while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
     array_push($arr, $row);
    }
    return $arr;
     }
     function end() { 
         @mysql_close(); 
     } 
 }
 
 $mysql = new mysql(); 
 $mysql->connect(); 
       // $query = $mysql->query("SELECT * FROM Employee");
 print_r($mysql->showresult(/*$query)*/$mysql->query("SELECT * FROM Employee"))); 
 $mysql->end();


Sunday, 4 March 2012

PHP MySQL Connection Test


Sometime it is necessary to make a test that PHP is working with MySQL.So after installing LAMP Server, try the following code to get the test done :


Click here


Then Write down the following codes:

mysql_connect("localhost", "root", "root") or die(mysql_error());
echo "Connected to MySQL
";
mysql_select_db("database_1.1") or die(mysql_error());
echo "Connected to Database
";

$result = mysql_query("SELECT * FROM Employee");

$row = mysql_fetch_array( $result );
// Print out the contents of the entry 

echo "FirstName: ".$row['first_name'];
echo "Last Name: ".$row['last_name'];


If you run the script from the browser:

localhost/test.php

You will see something like :



Creating MySQL Table

I will try to use this archive to use with other database related example:
CREATE TABLE Employee(
     id            int,
     first_name    VARCHAR(15),
     last_name     VARCHAR(15),
     start_date    DATE,
     end_date      DATE,
     salary        FLOAT(8,2),
     city          VARCHAR(10),
     description   VARCHAR(15)
 );


insert into Employee(id,first_name, last_name, start_date, end_Date,   
salary,  City, Description)
              values (1,'Jack',    'Schrvaski',  '19990720',  '20110721', 
1224.56, 'Toronto',  'Programmer');


insert into Employee(id,first_name, last_name, start_date, end_Date, 
  salary,  City,       Description)
values (1,'David',    'Moron',  '19990720',  '20110721', 
1224.56, 'Toronto',  'Designer');

insert into Employee(id,first_name, last_name, start_date, end_Date,   
salary,  City,       Description)
values (1,'Eric',    'Ron',  '19980829',  '20110321', 
1114.56, 'Toronto',  'Tester');

insert into Employee(id,first_name, last_name, start_date, end_Date,   
salary,  City,       Description)
values (1,'Frost',    'Robert',  '19990110',  '20110710', 
1224.56, 'Toronto',  'Manager');



Installing LAMP Server with PHP5, MySQL5 and Apache2 on Ubuntu 11.10

Installing LAMP server could be little bit tricky and if it will not work for you for the first time it will become harder for the next time so please read and do the command step by step.I will not go to much details but I will try to make it ready for you.

First of all if you have just installed Ubuntu ,please do the following:
sudo su
apt-get update
apt-get upgrade

This may over 30 minute according to your internet speed.

Next you have to install PHP5

apt-get install php5


If you like to run php5 code from terminal,Please do:
apt-get install php5-cli

To check if it is working fine or not we must test before go farther.

Let's type

pico phpinfo.php
This will let you type in the terminal.Write the following :


Now Press Ctrl+ o.It will write the data so press ctrl + x to exit.Now type:
php phpinfo.php
It will give you lots of info about the installed php information.If you get that you are with me.



Installing MySQL5

First you have to do the following:
apt-get install mysql-server mysql-client

You will be asked to provide a password for the MySQL root user - this password is valid for the user root@localhost as well as root@server1.example.com, so we don't have to specify a MySQL root password manually later:

New password for the MySQL "root"
Repeat password for the MySQL "root"

What I recommend here is please open a new document and try to copy paste all the command for future reference.

By default MySQl can be run on terminal so you don't need extra lib for that.Let's check MySQL working or not.
sudo netstat -tap | grep mysql
When you run this command, you should see the following line or something similar:

tcp 0 0 localhost.localdomain:mysql *:* LISTEN -

If the server is not running correctly, you can type the following command to start it:

sudo /etc/init.d/mysql restart
Now run to login to your database:

mysql -h localhost -u root -proot
Caution:There is no space in between -proot where root is the password.
So I guess everything is running well.

Installing apache2


Apache2 is available as an Ubuntu package, therefore we can install it like this:

apt-get install apache2

Now if you type your local ip address which is like 192.168.x.x, you may see the image below:

or The following Error in the terminal:

"Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName"

Don't panic ,you are not lost.Please do the following:
pico /etc/apache2/httpd.conf
It will show no letter on the file.Write the following:

ServerName localhost

Now press ctrl +o and exit.If have to restart apache2 by typing :
sudo /etc/init.d/apache2 restart

Now if you type localhost in the browser the image below will come up and will say it's working!
Apache's default document root is /var/www on Ubuntu, and the configuration file is /etc/apache2/apache2.conf. Additional configurations are stored in subdirectories of the /etc/apache2 directory such as /etc/apache2/mods-enabled (for Apache modules), /etc/apache2/sites-enabled (for virtual hosts), and /etc/apache2/conf.d.

We need to install the apache php5 module so that they may work together.
apt-get install libapache2-mod-php5
/etc/init.d/apache2 restart
The document root of the default web site is /var/www.Please make phpinfo.php the same way we made before and save it.Then in your browser type:

localhost/phpinfo.php


It will show the info() of php5 like this where you can still see MySQL is missing:













To support php5 to work with some useful platform please type:
apt-get install php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl 


Now restart the apache and if you run phpinfo.php again you will see MySQL support is there.So you are done.

Recommendation:


It is always a good idea to install phpMyAdmin with LAMP to Manage your Database.Please install it by the following command:
apt-get install phpmyadmin

You will see the something like:

1.Web server to reconfigure automatically: apache2
2.There will b ea screen here just press ok.
3.Configure database for phpmyadmin with dbconfig-common? No

On the browser type :localhost/phpmyadmin
Login using username: root
password: root














Hope this information will help you.Please leave comment or help me to fix typos.

Saturday, 3 March 2012

PHP5 Class and Object


This a very simple class to understand php5. If you are new to OOP, it may take some time to understand but once you understand, you will Rock!Please read through cause details are given in comments.

class Employee{

        private $firstName;
        private $lastName;
        private $emploeeId;

        /*
         *Variable are private because you don't want them visible from other classes.
         *Hence we need the public function to pull the data.
         */
        public function __construct($fName,$lName,$eId){
                $this -> firstName = $fName;
                $this -> lastName = $lName;
                $this -> employeeId = $eId;
        }
        /*some of you may get a bit confused here.Question is why need __construct()?
         *Answer is you need to create object.That object will hold data reference.
         */
        public function getFirstName (){
                return $this -> firstName; 

        }
        public function getLastName (){
                return $this -> lastName; 

        }
        public function getEId (){
                return $this -> employeeId; 

        }
        /* All of these get() function are required to pull the 
         *data as you has made the variable private.
         * If your variable was public, you could call them using  
         *echo $a ->firstName;
         * But here you can not. It will show the following error:
         * Fatal error:  Cannot access private property Employee::       
        */
}
$a = new Employee ('Mahmudul','Mithun','000001');

        /* So $a is a new object which has the values of 
         *'Mahmudul','Mithun','000001'=>3 parameters
         *Which will transfer the value to the 
         *__construct('Mahmudul','Mithun','000001')
         *this method will make these local variable available 
         *to the global variable i.e private variables
         *So now the values are set and you can pull them using get()method.
        */ 
echo $a ->getFirstName()." ". $a ->getLastName()." ". $a ->getEId(); 



Hope this may help you a bit to understand.Please don't forget to give me some feedback.