PHP MVC CodeIgniter Laravel Core PHP MORE

How to Signup User using PHP MVC with example


In this example we using Models, Views, Controller Structure for Registering an users data.

CREATE TABLE IF NOT EXISTS `register` ( `id` int(11) NOT NULL, `user_name` varchar(50) NOT NULL, `email_id` varchar(50) NOT NULL, `password` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Here is the view file index.php under register folder, for displaying the form which will be used for registering users data.

views/register/index.php

index.php

<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo URL; ?>register/signup">
First name:<br>
<input type="text" name="user_name" >
<br>
Last name:<br>
<input type="text" name="email_id">
<br><br>
Password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" value="Submit">
</form> 
</body>
</html>

To Register data in the database first we have to create a Controller file.

controller/register.php

<?php

class Register extends Controller
{
public function __construct()
{
parent::__construct();
}
function index(){
$this->view->render('register/index');
}
function signup(){
$user_name=$_POST['user_name'];
$email_id=$_POST['email_id'];
$password=$_POST['password'];
$count=$this->model->check_user($user_name,$email_id);
if($count > 0){
echo 'This User Already Exists';
}
else{
$data = array(
'id' =>null,
'user_name' =>$_POST['user_name'],
'email_id' =>$_POST['email_id'],
'password' =>$_POST['password']
);
$this->model->insert_user($data);
}
header('location:index');
}

}

Here is the model file which we are using for Registering data to database.

The file register_model.php is created under Models folder

models/register_model.php

index_model.php

<?php
class Register_Model extends Model
{
public function __construct()
{
parent::__construct();
}
public function check_user($user_name,$email_id)
{
$result= $this->db->select("SELECT * FROM `register` WHERE user_name = '".$user_name."' OR email_id = '".$email_id."'");
$count = count($result);
return $count;
}
public function insert_user($data)
{
$this->db->insert('register', $data);
}

}
Path: localhost/project_folder_name/view_folder_name/view_filename Example: localhost/mvc/register/index