Last active
March 6, 2019 06:14
-
-
Save aligoren/7929957ea55cfa778ca64565244ef83b to your computer and use it in GitHub Desktop.
PHP Method Chaining with Database Sample.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DB | |
{ | |
private $select; | |
private $where; | |
private $where_and; | |
private $where_or; | |
public function select($select, $fields) | |
{ | |
$this->select = "SELECT $fields FROM $select"; | |
return $this; | |
} | |
public function where($condition, $eq) | |
{ | |
$this->where .= " $condition=$eq " ; | |
return $this; | |
} | |
public function where_and($condition, $eq) | |
{ | |
$this->where_and .= " AND $condition=$eq " ; | |
return $this; | |
} | |
public function where_or($condition, $eq) | |
{ | |
$this->where_or .= " OR $condition=$eq " ; | |
return $this; | |
} | |
public function show_query() | |
{ | |
$where = ($this->where) ? " WHERE " : ' '; | |
$query = $this->select; | |
$query .= $where; | |
$query .= $this->where; | |
$query .= $this->where_and; | |
$query .= $this->where_or; | |
return $query; | |
} | |
} | |
$db = new DB(); | |
echo $db->select('users as u', 'ali') | |
->where('u.username', 'admin') | |
->where_and('u.password', '123456') | |
->where_and('u.isAdmin', true) | |
->show_query(); | |
/* | |
Output: SELECT ali FROM users as u WHERE u.username=admin AND u.password=123456 AND u.isAdmin=1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment