Wednesday, November 2, 2011

Practical view of OOPs Concept in PHP and MySql

For the display of the Menu on each page which has been opened, there is created a class and declare their object on location where you want to display them in your php script.


PHP class script "menu.php":

class Menu{
function set_Menu()
{
echo"<a href='/default.php'>Home</a>";
echo " ";
echo"<a href='/tutorials.php'>Tutorials</a>";
}
}


PHP Script:

<div class="leftmenu">
<?php
include("menu.php");
$objVar = new Menu();
$objVar ->set_Menu();
?>
</div>

Here I have mentioned the few code blocks for relating to the database and it is reduced the complexity of the codings and software bugs.

<?php
//declare the parent class
class database
{
//create variable
var $con;
var $results;
public $msg;


//declare function for connecting database
function set_db()
{
//here is the code for connecting database
$this->con=mysql_connect("localhost","root","");
//end of the function
}

//declare getter function for connection to database
function get_db()
{
return $this->con;
//call another function if the connection was not established
return $this->get_exception();
}

//declare the exception function for the connection
function get_exception()
{
if (!$this->con)
  {
  return('Could not connect: ' . mysql_error());
  }
}

//declare the fucntion for selecting database
function select_db()
{
$this->db = mysql_select_db("lib_db", $this->con);
}

//declare the setter function for executing query
function set_query($query)
{
////sotring values by retriving parameter from the main php file
$this->results = mysql_query($query);
}

//declare the getter function for returning the values
function get_query()
{
return $this->results;
}

//declare the function for closing the mysql connection
function close_db()
{
//code for closing mysql connection
mysql_close($this->con);
}

function execute_query($sql)
{

if (!mysql_query($sql,$this->con))
  {
  return('Error: ' . mysql_error());
  }

}

function set_message($message)
{
$this->msg = $message;
}

function get_message()
{
return "<b><font size=5 type=verdana color=blue>".$this->msg."</font></b>";
}
}
 

Hereafter we call them at any time ,any location with any no of objects. See sample code...


//link class library
include("class_database.php");


//define object for the class
$objDB = new database();


//call their method for calling setter function
$objDB->set_db();


//calling getter function for connection
$objDB->get_db();


//calling the function for selecting database
$objDB->select_db();


//store all information after execute query.
$objDB->execute_query("INSERT INTO Books(TitleID,Notes)VALUES('$_POST[titleids]','$_POST[notes]')");

//calling setter function for message
$objDB->set_message("You have succesfully 1 record added");




No comments:

Post a Comment