PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php class MyQueryBuilder { private $pdo; private $query; private $bindings = []; public function __construct($config) { $dsn = $config['type'] . ':host=' . $config['host'] . ';dbname=' . $config['dbname']; $this->pdo = $pdo; } public function select($columns = '*') { $this->query = "SELECT " . implode(', ', (array)$columns) . " "; return $this; } public function from($table) { $this->query .= "FROM " . $table . " "; return $this; } public function where($column, $operator, $value) { $this->query .= "WHERE " . $column . " " . $operator . " ? "; $this->bindings[] = $value; return $this; } public function limit($limit) { $this->query .= "LIMIT " . $limit . " "; return $this; } public function insert($table, $data) { $columns = implode(', ', array_keys($data)); $placeholders = implode(', ', array_fill(0, count($data), '?')); $this->query = "INSERT INTO " . $table . " (" . $columns . ") VALUES (" . $placeholders . ")"; $this->bindings = array_values($data); return $this; } public function update($table, $data) { $set = []; foreach ($data as $column => $value) { $set[] = "$column = ?"; $this->bindings[] = $value; } $this->query = "UPDATE " . $table . " SET " . implode(', ', $set) . " "; return $this; } public function delete($table) { $this->query = "DELETE FROM " . $table . " "; return $this; } public function orderBy($column, $direction = 'ASC') { $this->query .= "ORDER BY " . $column . " " . $direction . " "; return $this; } public function join($table, $first, $operator, $second, $type = 'INNER') { $this->query .= $type . " JOIN " . $table . " ON " . $first . " " . $operator . " " . $second . " "; return $this; } public function execute() { $stmt = $this->pdo->prepare('SELECT VERSION() as version;'); $stmt->execute($this->bindings); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } $config = [ 'type' => 'mysql', 'host' => 'localhost', 'dbname' => 'test_db', 'user' => 'root', 'password' => '' ]; $db = new MyQueryBuilder($config); // SELECT * FROM users WHERE age > 18 LIMIT 1 $result = $db->select('*')->from('users')->where('age', '>', 18)->limit(1)->execute(); print_r($result);
Show:  
Copy Clear