3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Query { private $select; private $from; private $where = []; /** * Defines the column list (SELECT {$columns}) * * @param string $columns * @return this */ public function select($columns) { $this->select = $columns; return $this; } /** * Defines the table to select from (SELECT * FROM {$table}) * * @param string $table * @return this */ public function from($table) { $this->from = $table; return $this; } /** * List of conditions to AND (key = column, value = value) * e.g. $query->where(['name' => 'bob']) * * @param mixed[string] $conditions * @return $this */ public function where(array $conditions) { $this->where = $conditions; return $this; } /** * Adds an AND condition * * @param string $column * @param mixed $value * @return this */ public function where_and($column, $value) { $this->where[$column] = $value; return $this; } /** * Builds and executes the query, returning a PDOStatement * * @return PDOStatement */ public function execute() { $query = sprintf( 'SELECT %s FROM %s', $this->select, $this->from ); $placeholders = array(); if (!empty($this->where)) { $query .= ' WHERE '; $index = 0; foreach ($this->where as $column => $value) { if ($index > 0) { $query .= ' AND '; } $query .= sprintf('`%s`', $column); if ($value === null) { $query .= ' IS NULL'; } else { $placeholder = sprintf(':placeholder_%d', $index); $query .= ' = ' . $placeholder; $placeholders[$placeholder] = $value; } $index++; } } // $pdo = new PDO($dsn, $user, $pass, $opt); // $stmt = $pdo->prepare($query); // $stmt->execute($placeholders); // return $stmt; echo $query . "\n\n"; print_r($placeholders); } } class MyClass { public function getData($name, $club) { $query = new Query(); $query->select('name') ->from('users') ->where(['quote' => '1']); $this->getQueryPart($query); $result = $query->execute(); // return $result->fetchAll(PDO::FETCH_ASSOC); } protected function getQueryPart($query) { $query->where_and('email', 'email@foobar.com') ->where_and('status', 1); } } $my_class = new MyClass(); $data = $my_class->getData('name', 'club'); // print_r($data);
Output for 7.0.0 - 7.0.23, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
SELECT name FROM users WHERE `quote` = :placeholder_0 AND `email` = :placeholder_1 AND `status` = :placeholder_2 Array ( [:placeholder_0] => 1 [:placeholder_1] => email@foobar.com [:placeholder_2] => 1 )

preferences:
115.95 ms | 404 KiB | 194 Q