Basic knowledge is always very important, in this article I will introduce to you how lớn use the PHP – MVC model, using PDO khổng lồ connect to MySQL.

Bạn đang xem: Complete login & register system using mvc & pdo

What is PDO? 

It is an acronym for “PHP Data Objects”. Until now, the functions used were divided according to lớn the type of database.

For example:

– When connecting lớn MySQL, I used khổng lồ connect with the “mysql_connect” function,– In the case of PostgreSQL, it was connected with the “pg_connect” function.

There is no problem if the database is fixed, but if you change or port to lớn a different database in the future, you have to rewrite everything.

Xem thêm: Cách Cắm Hoa Trong Lọ Thủy Tinh Cao, Bạn Biết Chưa?

But if you use the PDO class, the same function can be used regardless of which database is used, so if you change the database in the future, you only need khổng lồ change the parameters you specified when you created the PDO class (it seems that there are some differences depending on the database…)

Let’s learn how khổng lồ connect khổng lồ a database using the PDO class in this article.

We will proceed on the premise of the following conditions:

* PHP is PHP 5.3.6 or higher* Database is MySQL* Character encoding is UTF-8


6. Finally, we create the index.php và routes.php tệp tin in the root directory. Router file to do the navigation.

– index.php


if (isset($_GET<‘controller’>)) $controller = $_GET<‘controller’>;if (isset($_GET<‘action’>)) $action = $_GET<‘action’>; else $action = ‘index’; else $controller = ‘pages’;$action = ‘home’;


– routes.php

$controllers = array(‘users’ => <‘index’, ‘create’, ‘edit’, ‘store’, ‘update’, ‘delete’>,);

if (!array_key_exists($controller, $controllers) || !in_array($action, $controllers<$controller>)) $controller = ‘pages’;$action = ‘error’;

if (strpos($controller, ‘users’) !== false) include_once(‘controllers/’ . $controller . ‘Controller.php’);

$class = str_replace(‘_’, ”, ucwords($controller)) . ‘Controller’;$controller = new $class;$controller->$action();?>

So we have completed the basic PHP-MVC model, with the Data Select query using PDO. Next we will implement the insert, update, and delete models. The content will edit into the files we created above.

7. Edit UsersController

In the UsersController.php, showroom function create, edit, store, update and delete


require_once (‘controllers/BaseController.php’);require_once (‘models/user.php’);

class UsersController extends BaseController/*** Create view*/public function create()// It return địa chỉ view in views/users/create.php$this->render(‘add’);

/*** Store Action*/public function store()$result = User::store();

if ($result == $this->status_success) $_SESSION<‘alert_success’> = $this->save_success;echo ”; else $_SESSION<‘alert_danger’> = $this->save_error;echo ”;

/*** Edit view*/public function edit()// It return địa chỉ cửa hàng view in views/users/edit.php$user = User::find($id);$data = <‘user’ => $user>;$this->render(‘edit’, $data);

/*** Update Action*/public function update()$result = User::update();

if ($result == $this->status_success) $_SESSION<‘alert_success’> = $this->save_success;echo ”; else $_SESSION<‘alert_danger’> = $this->save_error;echo ”;

/*** Delete Action*/public function delete()$result = User::delete();

if ($result == $this->status_success) $_SESSION<‘alert_success’> = $this->delete_success;echo ”; else $_SESSION<‘alert_danger’> = $this->delete_error;echo ”;

8. In the model file models/user.php, showroom function find, store, update, delete


/*** Find*/public function find(int $id)$db = DB::getInstance();$sql = $db->prepare(“SELECT * FROM users WHERE id = ? “);$sql->execute(<$id>);$list = <>;if ($item = $sql->fetch()) // code …

return $list;

/*** Store Action*/public function store()try $db = DB::getInstance();// insert to lớn users table$sql = “INSERT INTO users (first_name, last_name, age) VALUES (?, ?, ?)”;$row = $db->prepare($sql);

if ($row->execute(<$first_name, $last_name, $age>)) $result = 1; // successful else $result = 0; // failed catch (PDOException $ex) $result = $ex->getMessage();return $result;

/*** Update Action*/public function update()try $db = DB::getInstance();// update to lớn users table$sql = “UPDATE users mix first_name = ?, last_name = ?, age = ? WHERE id = ?”;$row = $db->prepare($sql);

if ($row->execute(<$first_name, $last_name, $age, $id>)) $result = 1; // successful else $result = 0; // failed catch (PDOException $ex) $result = $ex->getMessage();return $result;

/*** Delete Action*/public function delete(int $id)try $db = DB::getInstance();// delete lớn users table$sql = “DELETE FROM users WHERE id = ?”;$row = $db->prepare($sql);

if ($row->execute(<$id>)) $result = 1; // successful else $result = 0; // failed catch (PDOException $ex) $result = $ex->getMessage();return $result;

9. In the views/users/ folder 

Create create.php, edit.php and edit index.php

– create.php and edit.php, simple code is below

// open form

// input đầu vào element

// Close form

– index.php


III. Conclusion

Our MVC code looks lượt thích this:

– controllers+ UsersController.php– models+ user.php– views+ users/create.php+ users/edit.php+ users/index.php+ layouts.php– connection.php– routes.php

Above is a simple PHP-MVC example, using PDO to manipulate MySQL, PDO also helps you avoid some SQL injection errors. So if you’re not using any PHP framework then giving PDO a try is a great option.