Friday 29 June 2012

Use Of Append Javascript

<html>
<head>
 <title>
 </title> 
 <!--Standard jQuery -->
 <script type="text/javascript" src="jquery.js" charset="utf-8"></script>
 <script type="text/javascript">
  $(document).ready(function()
  {
   $('#boxClear').click(function(){
    $('#firstFilterSearch').val('');

   });

   $('#firstFilterSearch').keyup(function()
   {
    var searchArea = $('#firstList');
    searchFirstList($(this).val(), searchArea);
   });

   $('#firstList').dblclick(function() {
    assignList();
   });

   $('#secondList').dblclick(function() {
    unassignList();
   });

   $('#to2').click(function()
   {
    assignList();
   });

   $('#to1').click(function()
   {
    unassignList();
   });
  });
   
  // Function for Filtering
  function searchFirstList(inputVal, searchArea)
  {
   var allCells = $(searchArea).find('option');
   if(allCells.length > 0)
   {
    var found = false;
    allCells.each(function(index, option)
    {
     var regExp = new RegExp(inputVal, 'i');
     if(regExp.test($(option).text()))
     {
      $(option).show();
     }
     else
     {
      $(option).hide();
     }
    });
   }
  }

  // function: UnAssignment
  function assignList()
  {
   $('#firstList :selected').each(function(i, selected){
    // append to second list box
    $('#secondList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
    // remove from first list box
    $("#firstList option[value='"+ selected.value +"']").remove();
   });
  }
  // function: UnAssignment
  function unassignList()
  {
   $('#secondList :selected').each(function(i, selected){
    // append to first list box
    $('#firstList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
    // remove from second list box
    $("#secondList option[value='"+ selected.value +"']").remove();
   });
  }
 </script>


</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%"> 
 <tr>  
  <td width="100%">
   <form id="frm_format" method="" action="">
   <table cellpadding="0" id="tbl_format"cellspacing="0" border="0" width="100%" class="standard_table_v4"> 
    <thead>
    </thead>
    <tbody>
     <tr>
      <td>
      <td align="center">
       Filter: <input id="firstFilterSearch" type="text">
         <input type="button" id="boxClear" name="boxClear" value="Cancel"><br>
       <select id="firstList" multiple="multiple" style="height:420px;width: 250px;" > 
        <option value="1">PHP</option>
        <option value="2">.Net</option>
        <option value="3">Copy</option>
        <option value="4">Paste</option>
        <option value="5">Pea</option>
        <option value="6">Pamp</option>
        <option value="7">ladaku</option>
        <option value="8">Zebra</option>
       </select>
      </td>
      <td align="center">
       <input id="to2" type="button" name="to2"  title='assign' value=">" /><br/><br/>
       <input id="to1" type="button" name="to1" title='unassign' value="<">
      </td>
      <td>
       <select id="secondList" multiple="multiple" style="height:420px;width: 250px;" >
       </select>
      </td>
     </tr>
    </tbody>
   </table>
   </form>
   
  </td>
 </tr>
</table>
</body>
</html>

Friday 22 June 2012

Ajax Autocomplete – Jquery PHP Mysql


Before Start

The aim is to design an auto complete script for text box in ajax using Jquery, PHP, Mysql. I have searched for the script, and i have found a simple autocomplete plugin here http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and you can find the documentation here http://docs.jquery.com/Plugins/Autocomplete.
You can download the source and see the Demos. But there is no demo fetching data from mysql. Then i have done some small trick in the php file to get data from mysql. This will be very useful in search suggestions, City, State fill up in some registrations.

HTML – Understanding the Layout

Here i have taken course names for example. I have a text box named and ided course. Thats all you need to know in the html layout.
<input type="text" name="course" id="course" />

JS – Include autocomplete plugin and activate

Download the autocomplete source from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and get the jquery core, autocomplete javascript file and css file. Include them inside the head tag. After that write some code to activate the text box with autocomplete.
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
 
<script type="text/javascript">
$().ready(function() {
    $("#course").autocomplete("get_course_list.php", {
        width: 260,
        matchContains: true,
        selectFirst: false
    });
});
</script>

To know the autocomplete plugin options go to here http://docs.jquery.com/Plugins/Autocomplete/autocomplete and see the Options tab.

PHP – Get data from DB

Get the query word and search within the database and return the list. (get_course_list.php file mentioned in the above javascript)
<?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
 
$sql = "select DISTINCT course_name as course_name from course where course_name LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $cname = $rs['course_name'];
    echo "$cname\n";
}
?>

Download

Download Source

Dynamically load mysql data using jquery and php


In this tutorial, I’ll be showing how you can dynamically retrieve data from mysql database using Jquery and Php. When I say dynamically, it means that there is no need to reload the page every time you try to access data from the database. This would be nice, since it will take lesser time for the user to actually see the results of his query.
Requirements:
  • Basic knowledge on Jquery
  • Basic knowledge on Php

I assume that you already know how to retrieve data from mysql database using Php. And basic knowledge of using Jquery.
First thing that you need to do is to import Jquery library:
<script type="text/javascript" src="../js/jq.js"></script>
Then create an input box. Where the user will input his query:
<input type="text" id="inp" name="inp"/></span>
Then create a div which we will use later to display the results:

<div class="results"></div>
Declare another script on the head portion of your project:

<script type="text/javascript">
 
 
</script>
Inside the new script that you’ve just created. Declare a function that would listen to the keyup event.

$(function(){
 
    $(#inp).keyup(function(){
 
    });
 
});
Here’s what happens. The function that you have declared will monitor any changes to the input box which has the id ‘inp’. And every time you hit any key on the keyboard. The action which is to be performed inside that event will be executed.
Inside the keyup function. Declare a variable that would store the value which is inputted in the input box.

var inpvalue= $('#inp').val();
Next thing that you need to do, is to declare another jquery function. This is the most important part of this tutorial, since this will be the one who will actually fetch the value from the database.

$.ajax({
    type: 'POST',  
    data: ({p : inpval}),
    url: 'listercust.php',
    success: function(data) {
         $('.result').html(data); 
 });
Here’s the code explanation:
  • type: the form method. This will either be POST or GET. POST is more secure than GET. Since users will be able to modify the data directly from the url if you use GET. And if you use POST, data will be hidden and you won’t be able to modify or tamper it.
  • data: this is the data that will be passed to the sql query in the php file that you will specify in the url.
  • url: this is the actual php file which has the query in it. Be sure to define everything that you need to actually query the database in this file.
  • success: this is where you define the callback function. A callback function is the function that will be called after the ajax function executed perfectly. This is where you will display the actual result that has been generated by the php file.
Then all you have to do now is to display the result of the query by changing the html property of the div with the class result. And the parameter would be the data fetched from the ajax function:

$('.result').html(data);
Overall this is what the code will look like:
$(function(){
            $('#inp').keyup(function(){
    
            var inpval=$('#inp').val();
                
            $.ajax({
                type: 'POST',
                data: ({p : inpval}),
                url: 'listercust.php',
                success: function(data) {
                     $('.result').html(data);
            
          }
        });
    });
});

The php file

The  second part of this tutorial would be the the php file that has the query on it.
First thing that you need to do is to declare all the connections needed to connect to the database. I won’t be discussing it here since its  one of the basics.
Declare a php variable that would receive the value from the ajax function that you have created earlier. Remember that the parameter ‘p’   should match the value that you declared on the ajax function.

$name=$_POST['p'];
This part of the function:

data: ({p : inpval}),
All you have to do now is to make a query that would use the data inputted by the user:

$query=mysql_query("SELECT * FROM table 
WHERE fieldx like '$name%'");
Then display the fetch values:
while($row=mysql_fetch_assoc($query)){
    $row['name'];
 
}

Conclusion
That is how you fetch data dynamically from mysql database using jquery.

Thursday 21 June 2012

working tutorial on "Adding new input field dynamiclly using Javascript DOM"


##################
#### Dpz code #####
##################







<script type="text/javascript">
fields1=0;

function createInput1(){
    if(fields1!=10){
var input = document.createElement('input'); <1-- it creates input Element -->
input.type = 'text';
input.value = '';
input.name='item[]';  <!--Put the input field name according to your requirement -->

document.getElementById("text1").appendChild(input); <!-- the DIV ID or any ID where u want your input field will be placed comes here.. -->
fields1 += 1;}
 else { 
   
document.getElementById("txt1").innerHTML += "<br />Maximum 10 fields allowed."; <!--Use this else condition only if u want to limit/stop adding new fields -->
document.form1.add1.disabled=true;
}


}
</script>


<form name="form1" id="form1" action="" method="post"><table align="center">
<tr><td>Country :</td><td><input type="text" name="item[]"/></td></tr>

<tr><td></td><td><div id="text1"  style="width:100px" align="center"></div></td></tr>
<tr><td colspan="2"><div id="txt1"  style="width:200px" align="center"></div></td></tr>

<tr><td><input name="submit" type="submit" value="ADD" /></td><td><input name="add1" type="button" value="Add More Country" onClick="createInput1();" /></td></tr> <!--this will trigger createInput1 function when the button is clicked -->
</table>

</form>

Wednesday 13 June 2012

PHP for Beginners: Building Your First Simple CMS

PHP for Beginners: Building Your First Simple CMS

Jan 5 2009

The Magic of PHP + MySQL


It's safe to say that nearly every website that's up-to-date these days is using some form of content management system (CMS). While there are a ton of great free options that provide us with a CMS to power a website (WordPress, Drupal, etc.), it doesn't hurt to peek under the hood and get a feel for how these systems work.
To get our feet wet as back-end developers, we'll be creating a simple PHP class that will:
  • Create a database
  • Connect to a database
  • Display a form with two fields
  • Save the form data in the database
  • Display the saved data from the database



This class is intended to give you a feel for how PHP and MySQL interact together, and to show the basics of a CMS. I'll be skipping explanations of some of the very basic programming stuff, so if at any point you feel lost, head on over to w3schools.com and give yourself a crash-course in PHP. I'll try not to lose anyone, though, I promise.

Building the Class


Our first step is to simply lay out the class in a file named 'simpleCMS.php' so we have a road map to work with.
<?php

class simpleCMS {
  var $host;
  var $username;
  var $password;
  var $table;

  public function display_public() {

  }

  public function display_admin() {

  }

  public function write() {

  }

  public function connect() {

  }

  private function buildDB() {

  }
}

?>
As you can see, we're creating one class with four variables and five methods. I've opted to use PHP's object-oriented approach because it makes for cleaner code in large projects, and, in my opinion, it's just good practice.

The Variables

In this case, all four variables are for connecting to the database: $host, $username, $password, and $table provide a path and access to our database on the server. For now, we'll leave those empty and move on to our database, which is constructed by the method buildDB().

Build the Database

private function buildDB() {
    $sql = <<<MySQL_QUERY
        CREATE TABLE IF NOT EXISTS testDB (
            title VARCHAR(150),
            bodytext TEXT,
            created VARCHAR(100)
    )
    MySQL_QUERY;

    return mysql_query($sql);
}
This function runs a MySQL command that checks the database to see if testDB exists. If so, it simply passes along a notification of success; if not, it creates our table and assigns three columns to hold data.

Connect to the Database


Now that we have a function to build our table, let's create the function that will connect to our database.
public function connect() {
    mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
    mysql_select_db($this->table) or die("Could not select database. " . mysql_error());

    return $this->buildDB();
}
We call mysql_connect() to hook into our database, and then mysql_select_db() to make sure we save our data in the right place. Both of these functions are accompanied by the die() command, which essentially says, "in the event that this function fails, stop execution of this script and display a message."
Our connect() function connects to the database and gets us pointed in the right direction, then runs our buildDB() function. Remember the grammatically awkward "IF NOT EXISTS" part of our MySQL command? Because we're going to run this function every time the page is loaded, we have to make sure we're not overwriting our database with every function call, and that's exactly what that phrase requires.

Build the Form

So, we've got a database. Now we just need to put stuff in it!
public function display_admin() {
    return <<<ADMIN_FORM

    <form action="{$_SERVER['PHP_SELF']}" method="post">
      <label for="title">Title:</label>
      <input name="title" id="title" type="text" maxlength="150" />
      <label for="bodytext">Body Text:</label>
      <textarea name="bodytext" id="bodytext"></textarea>
      <input type="submit" value="Create This Entry!" />
    </form>

ADMIN_FORM;
  }
Again, this is a very simple function. When called, it simply returns the HTML markup to create our form. You'll notice, however, in the action attribute of the form element, that I've used the variable $_SERVER['PHP_SELF']. This is, essentially, a shortcut that references the file you're currently using (in our case, it's display.php). This is useful if you'll be reusing your code across a site and don't necessarily want to rewrite this function for each page.
I'm also going to take a second right now to talk about the method I'm using to return the HTML. It's a format used in PHP called HEREDOC syntax, and I love it.
The primary advantage of HEREDOC is that it allows you to include formatting in your output. This is extraordinarily useful for folks like me who take issue with cluttered source code. You can read more about HEREDOC syntax and its ilk in the PHP manual.

Saving the Data to the Database

Our form will allow us to input information, so how do we save it? That's where our write() method comes in.
public function write($p) {
    if ( $p['title'] )
      $title = mysql_real_escape_string($p['title']);
    if ( $p['bodytext'])
      $bodytext = mysql_real_escape_string($p['bodytext']);
    if ( $title && $bodytext ) {
      $created = time();
      $sql = "INSERT INTO testDB VALUES('$title','$bodytext','$created')";
      return mysql_query($sql);
    } else {
      return false;
    }
}
Let's start with the function call itself—we're passing a variable to this one, which we haven't done so far. Our variable $p is going to hold the information sent from our form via the post method.
Once inside the function, we start with a conditional statement that's checking to see if the the title value was set in the form before it was submitted, and if so, we're setting our $title variable to the $_POST['title'] value (NOTE: we're using the function mysql_real_escape_string() as a precaution against potentially dangerous input, which is important to keep in mind when you're building anything that will allow users to input information). If $_POST['title'] wasn't set, we skip this line, leaving the $title variable unset.
This process is repeated for our second input, and then both variables are checked to make sure nothing is blank before saving to the database. If both variables are set, we then set the $created variable with the current Unix timestamp, which we'll use to sort our entries chronologically when we view them in the future.
We now have three variables, and because we've run checks, we know that all three variables are not empty. Now we can write our MySQL query that will save the entry in the database!

Displaying the Information from the Database


Now that we have the means to put information into our database, we need to create a way to get that information back out. This is where display_public() comes in. This is by far the most complex of our methods, so let's really take our time and figure out what's going on inside.
public function display_public() {
    $q = "SELECT * FROM testDB ORDER BY created DESC LIMIT 3";
    $r = mysql_query($q);

    if ( $r !== false && mysql_num_rows($r) > 0 ) {
      while ( $a = mysql_fetch_assoc($r) ) {
        $title = stripslashes($a['title']);
        $bodytext = stripslashes($a['bodytext']);

        $entry_display .= <<<ENTRY_DISPLAY

    <h2>$title</h2>
    <p>
      $bodytext
    </p>

ENTRY_DISPLAY;
      }
    } else {
      $entry_display = <<<ENTRY_DISPLAY

    <h2>This Page Is Under Construction</h2>
    <p>
      No entries have been made on this page.
      Please check back soon, or click the
      link below to add an entry!
    </p>

ENTRY_DISPLAY;
    }
    $entry_display .= <<<ADMIN_OPTION

    <p class="admin_link">
      <a href="{$_SERVER['PHP_SELF']}?admin=1">Add a New Entry</a>
    </p>

ADMIN_OPTION;

    return $entry_display;
  }
The first thing to note when reading from a database is the way PHP and MySQL interact with each other. First, we ask the database a question (query), to which it replies with a result (resource). However, this result isn't really useful until we've decoded it using one of several methods that "fetch," or organize, the information that's contained inside into a usable form (array).
Our very first action in the above function is to set up our query in the variable $q. The asterisk (*) operator in MySQL means "everything," so our query is asking the database to select everything from entries in the table testDB in reverse chronological order, limited to the first three entries returned.
Now that the query is defined, we send it to the database using the function mysql_query(). The resulting resource is stored in the variable $r. This is where it gets a bit tricky.
We now run a conditional statement that says, "IF mysql_query() didn't fail, AND IF the number of entries returned was greater than zero, process the result, OR ELSE display a default message."
If $r contains entries from the database, we now have to "fetch" that data. Information from the database is returned as an array, which is organized similarly to the database table itself. The function mysql_fetch_assoc() will take the resource and break each entry into an associative array (this means that when we save the result of mysql_fetch_assoc() into the variable $a, the data from the entry will be accessible by the column names in the database, i.e. $a['title']).
However, mysql_fetch_assoc() only gives us one entry at a time. To get all of the returned entries, we have to use a while loop. Essentially, we're saying, "WHILE $r has values we haven't used yet, get the next entry in line and do the following actions with it."
In this case, we're going to check the entry to make sure that data was returned, then remove the slashes that were added when we saved the information to the database using stripslashes(). After that, we simply wrap the variables in some HTML and, voila! we've got screen-ready content!
As a final step, the code adds a link to the bottom that allows users to add an entry. It's worth noting the use of the ".=" operator used in the while loop and when creating the "Add a New Entry" link; a function can only return one variable, so we need to append the new information to the existing variable. If we just used the equals sign ("="), we would overwrite existing data and end up with just a link to the form and no content.
So, you've now written your first CMS class! You can easily write and retrieve data to and from a database. All that's left to do is to try it out!

Using the Class

To use our class, we need to create a separate file. I'm going to call it "display.php", which I'll save in the main web folder, with our class saved as "simpleCMS.php" in a folder called "_class" within the main folder. To start, we just set up a document with plain ol' HTML.
<html>

  <head>
    <title>SimpleCMS</title>
  </head>

  <body>

  </body>

</html>
To use our class, we just have to insert a little PHP between the body tags:
<?php

  include_once('_class/simpleCMS.php');
  $obj = new simpleCMS();
  $obj->host = 'database.host.net';
  $obj->username = 'DB1234567';
  $obj->password = 'DBpassword';
  $obj->table = 'DB1234567';
  $obj->connect();

  if ( $_POST )
    $obj->write($_POST);

  echo ( $_GET['admin'] == 1 ) ? $obj->display_admin() : $obj->display_public();

?>
First and foremost, we have to include the class using the include_once() function. Then, we have to instantiate our object so that our code knows what's going on. Third, we set all of those variables we talked about toward the beginning of this tutorial. You'll have to replace all of those values with the information you get from your own server or hosting company. And fourth, we connect to our database using the connect() method.
After we've connected to the database, we check to see if any $_POST information exists. This is because we're using the same file for input, processing, and display of information. If anything was passed via $_POST, we run the write() function to validate it and save it to the database. Then, we use some shorthand trickery to run a conditional statement. In essence, we're saying, "IF $_GET['admin'] is set to 1, then show the form using display_admin(), OR ELSE show me the stored entries using display_public()."
And that's it! Once you get a feel for it, this sort of basic programming will allow you to start exercising total control over websites you build, whether you decide to really dig in and build your own CMS framework or just improve an existing CMS by, say, writing a WordPress plugin.
Really, when it comes to modern web design, you should have at least some understanding of how things are working behind the curtain—understanding how a site works will better enable you to design sites that have a more fluid integration of form and function. And besides, adding PHP and MySQL to your curriculum vitae definitely won't hurt your credibility...


Jason Lengstorf runs Ennui Design, a freelance design and development effort. He has a fetish for building custom applications from scratch, including his own content management system. When he's not glued to his keyboard, he's likely to be wearing cowboy shirts, deadlifting, or pretending to know stuff about wine.

Important Note

This code is written for demonstration purposes only. Several security holes have been pointed out in the comments, which I have addressed in Part Two of this tutorial series Editor's note: There is no part two of this series anymore. Jason recommends his book PHP for Absolute Beginners as a resource for best practices. Still, I would strongly advise not using it for production websites without further testing. The demo has been removed.
I have covered some of the bases with security, but other issues may exist. Further reading on security risks and safe PHP code can be found here. Please read through this before implementing this code on your server to avoid potential security holes.

Model View Controller(MVC) in PHP






The model view controller pattern is the most used pattern for today’s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern.

Despite the fact that the MVC pattern is very popular in PHP, is hard to find a proper tutorial accompanied by a simple source code example. That is the purpose of this tutorial.

    The MVC pattern separates an application in 3 modules: Model, View and Controller:
  • The model is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application.
  • The view (presentation) is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications, like wordpress, joomla, …
  • The controller handles the model and view layers to work together. The controller receives a request from the client, invoke the model to perform the requested operations and send the data to the View. The view format the data to be presented to the user, in a web application as an html output.
The above figure contains the MVC Collaboration Diagram, where the links and dependencies between figures can be observed:
mvc-collaboration
Our short php example has a simple structure, putting each MVC module in one folder:
mvc-structure

Controller

The controller is the first thing which takes a request, parse it, initialize and invoke the model and takes the model response and send it to the presentation layer. It’s practically the liant between the Model and the View, a small framework where Model and View are plugged in. In our naive php implementation the controller is implemented by only one class, named unexpectedly controller. The application entry point will be index.php. The index php file will delegate all the requests to the controller:
  1. // index.php file  
  2. include_once("controller/Controller.php");  
  3.   
  4. $controller = new Controller();  
  5. $controller->invoke();  
Our Controller class has only one function and the constructor. The constructor instantiate a model class and when a request is done, the controller decide which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated.
  1. include_once("model/Model.php");  
  2.   
  3. class Controller {  
  4.      public $model;   
  5.   
  6.      public function __construct()  
  7.      {  
  8.           $this->model = new Model();  
  9.      }   
  10.   
  11.      public function invoke()  
  12.      {  
  13.           if (!isset($_GET['book']))  
  14.           {  
  15.                // no special book is requested, we'll show a list of all available books  
  16.                $books = $this->model->getBookList();  
  17.                include 'view/booklist.php'; 
  18.           } 
  19.           else 
  20.           { 
  21.                // show the requested book 
  22.                $book = $this->model->getBook($_GET['book']); 
  23.                include 'view/viewbook.php';  
  24.           }  
  25.      }  
  26. }  
In the following MVC Sequence Diagram it can be observed the flow during a http request:
mvc-sequence1

Model and Entity Classes

    The Model represents the data and the logic of an application, what many calls business logic. Usually, it’s responsible for:
  • storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is not an unusual at all.
  • encapsulating the application logic. This is the layer that should implement all the logic of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.
In our example the model is represented by 2 classes: the “Model” class and a “Book” class. The model doesn’t need any other presentation. The “Book” class is an entity class. This class should be exposed to the View layer and represents the format exported by the Model view. In a good implementation of the MVC pattern only entity classes should be exposed by the model and they should not encapsulate any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can be replaced by xml or json chunk of data. In the above snippet you can notice how Model is returning a specific book, or a list of all available books:
  1. include_once("model/Book.php");  
  2.   
  3. class Model {  
  4.     public function getBookList()  
  5.     {  
  6.         // here goes some hardcoded values to simulate the database  
  7.         return array(  
  8.             "Jungle Book" => new Book("Jungle Book""R. Kipling""A classic book."),  
  9.             "Moonwalker" => new Book("Moonwalker""J. Walker"""),  
  10.             "PHP for Dummies" => new Book("PHP for Dummies""Some Smart Guy""")  
  11.         );  
  12.     }  
  13.   
  14.     public function getBook($title)  
  15.     {  
  16.         // we use the previous function to get all the books and then we return the requested one.  
  17.         // in a real life scenario this will be done through a db select command  
  18.         $allBooks = $this->getBookList();  
  19.         return $allBooks[$title];  
  20.     }  
  21.   
  22. }  
In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.
  1. class Book {  
  2.     public $title;  
  3.     public $author;  
  4.     public $description;  
  5.   
  6.     public function __construct($title$author$description)  
  7.     {  
  8.         $this->title = $title;  
  9.         $this->author = $author;  
  10.         $this->description = $description;  
  11.     }  
  12. }  

View (Presentation)

The view(presentation layer)is responsible for formating the data received from the model in a form accessible to the user. The data can come in different formats from the model: simple objects( sometimes called Value Objects), xml structures, json, …
The view should not be confused to the template mechanism sometimes they work in the same manner and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the code. The controller delegate the data from the model to a specific view element, usually associated to the main entity in the model. For example the operation “display account” will be associated to a “display account” view. The view layer can use a template system to render the html pages. The template mechanism can reuse specific parts of the page: header, menus, footer, lists and tables, …. Speaking in the context of the MVC pattern
In our example the view contains only 2 files one for displaying one book and the other one for displaying a list of books.
viewbook.php
  1. <html>  
  2. <head></head>  
  3.   
  4. <body>  
  5.   
  6.     <?php   
  7.   
  8.         echo 'Title:' . $book->title . '<br/>';  
  9.         echo 'Author:' . $book->author . '<br/>';  
  10.         echo 'Description:' . $book->description . '<br/>';  
  11.   
  12.     ?>  
  13.   
  14. </body>  
  15. </html>  
booklist.php
  1. <html>  
  2. <head></head>  
  3.   
  4. <body>  
  5.   
  6.     <table>  
  7.         <tbody><tr><td>Title</td><td>Author</td><td>Description</td></tr></tbody>  
  8.         <?php   
  9.   
  10.             foreach ($books as $title => $book)  
  11.             {  
  12.                 echo '<tr><td><a href="index.php?book='.$book->title.'">'.$book->title.'</a></td><td>'.$book->author.'</td><td>'.$book->description.'</td></tr>';  
  13.             }  
  14.   
  15.         ?>  
  16.     </table>  
  17.   
  18. </body>  
  19. </html>  
The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server…
    This post should not be ended before enumerating the advantages of Model View Controller pattern:
  • the Model and View are separated, making the application more flexible.
  • the Model and view can be changed separately, or replaced. For example a web application can be transformed in a smart client application just by writing a new View module, or an application can use web services in the backend instead of a database, just replacing the model module.
  • each module can be tested and debugged separately.
The files are available for download as a zip from http://sourceforge.net/projects/mvc-php/files/mvc.zip/download

Difference between mysql_fetch_array,mysql_fetch_row and mysql_fetch_object

mysql_fetch_row ::Return row as aan enumrated array and each line contain a unique ID .example.
$result=mysql_query($query);
while($row=mysql_fetch_row($result))
{
print "$row[0]";
print "$row[1]";
print "$row[2]";
}

mysql_fetch_array ::Return row as anassociative or anenumrated arrayor both which is default .you can refer to outputs as databases fieldname rather then number.example.
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
print "$row['name']";
print "$row['address']";
print "$row['city']";
}

mysql_fetch_object :: it return as an object on the place of array.

$result=mysql_query($query);
while($row=mysql_fetch_object($result))
{
print "$row->name";
print "$row->address";
print "$row->city";
}


Explained:


mysql_fetch_array:
--> it returns array as index as table field name as well as it's index number
from table student you fetch record like this:
while($res=mysql_fetch_array($rs)){

    echo  $res['id'] ;// print id value
        or
    echo $res[0];// same as above statement
 
   

}

mysql_fetch_row:
--> it returns array as  it's index number
from table student you fetch record like this:
while($res=mysql_fetch_row($rs)){

 
    echo $res[0];// it can fetch value by index value not table field name
 
   

}



mysql_fetch_object
--> it returns array as  it's as object as table field name
from table student you fetch record like this:
while($res=mysql_fetch_object($rs)){

 
    echo $res->id;//  it can fetch value by object value not table field name or it's                                     //index
 
   

}


In order to for you to know which to use you'll need to know what each of the above returns.

mysql_fetch_assoc - returns an associative array of your field names eg $row['field_name_here']

mysql_fetch_row - returns a numeric array eg $row[0] returns the first column, $row[1] returns the second column etc.

However mysql_fetch_array retuns both an associative and numeric array.

I personally use mysql_fetch_assoc or mysql_fetch_array.