MVC- How can we insert the data in database using MVC in PHP?

MVC(Model View Controller) have.

1) Model class

2) View (HTML/css)

3) Controller class

MVC-View file

What we want to display on the the Browser, for example HTML,CSS,JavaScript etc. in view file.

First of all we have to created a form that are describes below and after that include controller class and get the request of a submit button and finally pass the data in a function.

include("controller.php");
// assign the object for controller class
$obj = new controller(); 
if(isset($_REQUEST('submit'))){
$n=$_REQUEST['name'];
$p=$_REQUEST['pass'];
// Pass the data in insert function
$obj->insert($n,$p); 
header("location:view.php");
}

Example: Below is our form. When we will enter value in name and Password and click on submit button then work above code. In this case we will get request the value of name and password.

name
password

MVC - Controller

Controller is the mediator of model & View that are connect the each other .

include("model.php");
class controller{
 public function insert($n,$p){
  $obj = new model();
  $obj->insert($n,$p);
 }
}

MVC - Model

Model is the database class that are interact with the database and response via controller on the view

class model{
 public function model(){
  mysql_connect("localhost","root","");
  mysql_select_db("mvc");
 }
 public function insert($n,$p){
  $ins ="insert into user (name,pass) values('$n','$p')";
  $rs= mysql_query($ins);
 }
}

No comments:

Post a Comment