0% found this document useful (0 votes)
154 views

2 - PHP MVC Frameworks MVC Introduction Lab

This document describes building a basic PHP MVC framework without using an existing framework. It includes 3 sections: 1. Configuring the database connection and basic controller. 2. Creating a model class to interface with the database using methods like insert, update, delete. 3. Building a controller class to handle requests and call the appropriate model methods or views. The framework allows creating, reading, updating and deleting sports records in a database table to demonstrate basic MVC functionality without relying on an external framework.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views

2 - PHP MVC Frameworks MVC Introduction Lab

This document describes building a basic PHP MVC framework without using an existing framework. It includes 3 sections: 1. Configuring the database connection and basic controller. 2. Creating a model class to interface with the database using methods like insert, update, delete. 3. Building a controller class to handle requests and call the appropriate model methods or views. The framework allows creating, reading, updating and deleting sports records in a database table to demonstrate basic MVC functionality without relying on an external framework.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

MySQL PHP MVC CRUD Without

Framework
Introduction
This tutorial is for beginners or students. I created a functionality to add, edit and delete a record
in PHP with MVC logic without Framework. Also, it explained how to create an MVC pattern in
PHP. I hope it will be helpful for you to add a data table in your program.

Building Our MVC Framework Pattern in PHP


 
You might be wondering why we would even need to create our own framework when there are
already so many good choices out there. The reason for this is so that we can gain an
understanding of the underlying principles of MVC.

As we learn more about these principles, we will grow in our understanding of why the excellent
MVC frameworks do things the way they do. We are not learning how to create an application in
Zend Framework, or in CakePHP. We are learning how MVC works, and by extension, how
these frameworks have built upon (or deviated from) the way in which we would expect an MVC
framework to be built.

PROJECT WEB - WEBG301 1


MVC Model & PHP MVC Project Structure

In PhpMyAdmin, create a database named php_mvc_demo then create a table named sports

Section 1
 
Config.php is used to connect the mysql database to create a connection parameter for mysql
host,user,password and database name.
<?php
class config

PROJECT WEB - WEBG301 2


{
function __construct() {
$this->host = "localhost";
$this->user = "root";
$this->pass = "";
$this->db = "php_mvc_demo";
}
}
?>

A small part of the code in index.php is used to setup a controller object and call mvcHandler() to
view the default page list.php.

<?php
session_unset();
require_once 'controller/sportsController.php';
$controller = new sportsController();
$controller->mvcHandler();
?>

In the model folder, create one class for table structure, its named sports and has field and
message field to hold messages and data. 
<?php
class sports
{
// table fields
public $id;
public $category;
public $name;
// message string
public $id_msg;
public $category_msg;
public $name_msg;
// constructor set default value
function __construct()
{
$id=0;
$category=$name="";
$id_msg=$category_msg=$name_msg="";
}
}
?>

Section 2
 
The second section is a sportsModel class structure. We are going to explain and show
insertRecord(), updateRecord(),selectRecord() and insertRecord(). The sportsModel class is used

PROJECT WEB - WEBG301 3


to access the function sportsController. The sportsModel class constructor receives a mysql
connection parameter to work with the database.

<?php

class sportsModel
{
// set database config for mysql
function __construct($consetup)
{
$this->host = $consetup->host;
$this->user = $consetup->user;
$this->pass = $consetup->pass;
$this->db = $consetup->db;
}
// open mysql data base
public function open_db()
{
$this->condb=new mysqli($this->host,$this->user,$this->pass,$this->db);
if ($this->condb->connect_error)
{
die("Error in connection: " . $this->condb->connect_error);
}
}
// close database
public function close_db()
{
$this->condb->close();
}

// insert record
public function insertRecord($obj)
{
try
{
$this->open_db();
$query=$this->condb->prepare("INSERT INTO sports (category,name)
VALUES (?, ?)");
$query->bind_param("ss",$obj->category,$obj->name);
$query->execute();
$res= $query->get_result();
$last_id=$this->condb->insert_id;
$query->close();
$this->close_db();
return $last_id;
}
catch (Exception $e)
{
$this->close_db();
throw $e;
}
}
//update record
public function updateRecord($obj)

PROJECT WEB - WEBG301 4


{
try
{
$this->open_db();
$query=$this->condb->prepare("UPDATE sports SET category=?,name=?
WHERE id=?");
$query->bind_param("ssi", $obj->category,$obj->name,$obj->id);
$query->execute();
$res=$query->get_result();
$query->close();
$this->close_db();
return true;
}
catch (Exception $e)
{
$this->close_db();
throw $e;
}
}
// delete record
public function deleteRecord($id)
{
try{
$this->open_db();
$query=$this->condb->prepare("DELETE FROM sports WHERE id=?");
$query->bind_param("i",$id);
$query->execute();
$res=$query->get_result();
$query->close();
$this->close_db();
return true;
}
catch (Exception $e)
{
$this->closeDb();
throw $e;
}
}
// select record
public function selectRecord($id)
{
try
{
$this->open_db();
if($id>0)
{
$query=$this->condb->prepare("SELECT * FROM sports WHERE id=?");
$query->bind_param("i",$id);
}
else
{$query=$this->condb->prepare("SELECT * FROM sports"); }

$query->execute();
$res=$query->get_result();
$query->close();
$this->close_db();

PROJECT WEB - WEBG301 5


return $res;
}
catch(Exception $e)
{
$this->close_db();
throw $e;
}

}
}

?>

Section 3
 
Section 3 is the controller code part. The sportsController has mvcHandler() and the CRUD
functions insert(), update(),delete() and list(). mvcHandler() receives request and execute. This
request shows views according to call request by user.

<?php
require 'model/sportsModel.php';
require 'model/sports.php';
require_once 'config.php';

session_status() === PHP_SESSION_ACTIVE ? TRUE : session_start();

class sportsController
{

function __construct()
{
$this->objconfig = new config();
$this->objsm = new sportsModel($this->objconfig);
}
// mvc handler request
public function mvcHandler()
{
$act = isset($_GET['act']) ? $_GET['act'] : NULL;
switch ($act)
{
case 'add' :
$this->insert();
break;
case 'update':
$this->update();
break;
case 'delete' :
$this -> delete();
break;
default:
$this->list();

PROJECT WEB - WEBG301 6


}
}
// page redirection
public function pageRedirect($url)
{
header('Location:'.$url);
}
// check validation
public function checkValidation($sporttb)
{ $noerror=true;
// Validate category
if(empty($sporttb->category)){
$sporttb->category_msg = "Field is empty.";
$noerror=false;
} elseif(!filter_var($sporttb->category, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$sporttb->category_msg = "Invalid entry.";
$noerror=false;
}else{$sporttb->category_msg ="";}
// Validate name
if(empty($sporttb->name)){
$sporttb->name_msg = "Field is empty.";
$noerror=false;
} elseif(!filter_var($sporttb->name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$sporttb->name_msg = "Invalid entry.";
$noerror=false;
}else{$sporttb->name_msg ="";}
return $noerror;
}
// add new record
public function insert()
{
try{
$sporttb=new sports();
if (isset($_POST['addbtn']))
{
// read form value
$sporttb->category = trim($_POST['category']);
$sporttb->name = trim($_POST['name']);
//call validation
$chk=$this->checkValidation($sporttb);
if($chk)
{
//call insert record
$pid = $this -> objsm ->insertRecord($sporttb);
if($pid>0){
$this->list();
}else{
echo "Somthing is wrong..., try again.";
}
}else
{
$_SESSION['sporttbl0']=serialize($sporttb);//add session obj
$this->pageRedirect("view/insert.php");
}

PROJECT WEB - WEBG301 7


}
}catch (Exception $e)
{
$this->close_db();
throw $e;
}
}
// update record
public function update()
{
try
{
if (isset($_POST['updatebtn']))
{
$sporttb=unserialize($_SESSION['sporttbl0']);
$sporttb->id = trim($_POST['id']);
$sporttb->category = trim($_POST['category']);
$sporttb->name = trim($_POST['name']);
// check validation
$chk=$this->checkValidation($sporttb);
if($chk)
{
$res = $this -> objsm ->updateRecord($sporttb);
if($res){
$this->list();
}else{
echo "Somthing is wrong..., try again.";
}
}else
{
$_SESSION['sporttbl0']=serialize($sporttb);
$this->pageRedirect("view/update.php");
}
}elseif(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
$id=$_GET['id'];
$result=$this->objsm->selectRecord($id);
$row=mysqli_fetch_array($result);
$sporttb=new sports();
$sporttb->id=$row["id"];
$sporttb->name=$row["name"];
$sporttb->category=$row["category"];
$_SESSION['sporttbl0']=serialize($sporttb);
$this->pageRedirect('view/update.php');
}else{
echo "Invalid operation.";
}
}
catch (Exception $e)
{
$this->close_db();
throw $e;
}
}
// delete record
public function delete()
{

PROJECT WEB - WEBG301 8


try
{
if (isset($_GET['id']))
{
$id=$_GET['id'];
$res=$this->objsm->deleteRecord($id);
if($res){
$this->pageRedirect('index.php');
}else{
echo "Somthing is wrong..., try again.";
}
}else{
echo "Invalid operation.";
}
}
catch (Exception $e)
{
$this->close_db();
throw $e;
}
}
public function list(){
$result=$this->objsm->selectRecord(0);
include "view/list.php";
}
}
?>

Section Four
 
Section four is the view part, when mvcHandler() receives a request and executes the request, it
shows views for user. We have created three views in the view folder, which is insert, update and
list, which all have HTML design. These views work with controller, and the controller works
with model to get or set records in a database table.

insert.php

<?php
require '../model/sports.php';
session_start();
$sporttb=isset($_SESSION['sporttbl0'])?
unserialize($_SESSION['sporttbl0']):new sports();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="../libs/bootstrap.css">
<style type="text/css">
.wrapper{

PROJECT WEB - WEBG301 9


width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Add Sports</h2>
</div>
<p>Please fill this form and submit to add sports record in the
database.</p>
<form action="../index.php?act=add" method="post" >
<div class="form-group <?php echo (!empty($sporttb-
>category_msg)) ? 'has-error' : ''; ?>">
<label>Sport Category</label>
<input type="text" name="category" class="form-control"
value="<?php echo $sporttb->category; ?>">
<span class="help-block"><?php echo $sporttb-
>category_msg;?></span>
</div>
<div class="form-group <?php echo (!empty($sporttb-
>name_msg)) ? 'has-error' : ''; ?>">
<label>Sports Name</label>
<input name="name" class="form-control" value="<?php echo
$sporttb->name; ?>">
<span class="help-block"><?php echo $sporttb->name_msg;?
></span>
</div>
<input type="submit" name="addbtn" class="btn btn-primary"
value="Submit">
<a href="../index.php" class="btn btn-default">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

PROJECT WEB - WEBG301 10


list.php

<?php session_unset();?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link href="~/../libs/fontawesome/css/font-awesome.css" rel="stylesheet"
/>
<link rel="stylesheet" href="~/../libs/bootstrap.css">
<script src="~/../libs/jquery.min.js"></script>
<script src="~/../libs/bootstrap.js"></script>
<style type="text/css">
.wrapper{
width: 650px;
margin: 0 auto;
}
.page-header h2{
margin-top: 0;
}
table tr td:last-child a{
margin-right: 15px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>

PROJECT WEB - WEBG301 11


<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<a href="index.php" class="btn btn-success pull-
left">Home</a>
<h2 class="pull-left">Sports Details</h2>
<a href="view/insert.php" class="btn btn-success pull-
right">Add New Sports</a>
</div>
<?php
if($result->num_rows > 0){
echo "<table class='table table-bordered table-
striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Sports Category</th>";
echo "<th>Sports Name</th>";
echo "<th>Action</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>";
echo "<a href='index.php?act=update&id=".
$row['id'] ."' title='Update Record' data-toggle='tooltip'><i class='fa
fa-edit'></i></a>";
echo "<a href='index.php?act=delete&id=".
$row['id'] ."' title='Delete Record' data-toggle='tooltip'><i class='fa
fa-trash'></i></a>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "<p class='lead'><em>No records were
found.</em></p>";
}
?>
</div>
</div>
</div>
</div>
</body>
</html>

PROJECT WEB - WEBG301 12


update.php
<?php
require '../model/sports.php';
session_start();
$sporttb=isset($_SESSION['sporttbl0'])?
unserialize($_SESSION['sporttbl0']):new sports();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="../libs/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Sports</h2>
</div>
<p>Please fill this form and submit to add sports record in the
database.</p>
<form action="../index.php?act=update" method="post" >
<div class="form-group <?php echo (!empty($sporttb-
>category_msg)) ? 'has-error' : ''; ?>">
<label>Sport Category</label>
<input type="text" name="category" class="form-control"
value="<?php echo $sporttb->category; ?>">

PROJECT WEB - WEBG301 13


<span class="help-block"><?php echo $sporttb-
>category_msg;?></span>
</div>
<div class="form-group <?php echo (!empty($sporttb-
>name_msg)) ? 'has-error' : ''; ?>">
<label>Sports Name</label>
<input type="text" name="name" class="form-control"
value="<?php echo $sporttb->name; ?> ">
<span class="help-block"><?php echo $sporttb->name_msg;?
></span>
</div>
<input type="hidden" name="id" value="<?php echo $sporttb-
>id; ?>"/>
<input type="submit" name="updatebtn" class="btn btn-primary"
value="Submit">
<a href="../index.php" class="btn btn-default">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

PROJECT WEB - WEBG301 14

You might also like