Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Class SQLBuilder
*/
class SQLBuilder
{
private $from_table = null;
/** @var array */
private $select_columns = [];
public function clear()
{
$this->from_table = null;
$this->select_columns = [];
return $this;
}
public function from($table_name)
{
$this->from_table = $table_name;
return $this;
}
public function select($columns = '*')
{
if (is_string($columns)) {
$columns = explode(',', $columns);
}
foreach ($columns as $column) {
$column = trim($column);
if ($column) {
$this->select_columns[] = $column;
}
}
return $this;
}
public function text()
{
/* SQLインジェクション... */
return 'SELECT ' . $this->parse_select_columns() . ' FROM ' . $this->from_table;
}
private function parse_select_columns()
{
$select_columns = $this->select_columns;
if (empty($select_columns)) {
$select_columns = ['*'];
}
/* SQLインジェクション... */
return implode(',', $select_columns);
}
}
class MySQL_Connector
{
/**
* @param SQLBuilder $builder
*/
public function execute($builder)
{
echo $builder->text();
}
}
class User
{
/** @var MySQL_Connector */
private $connector;
/** @var SQLBuilder $builder */
private $builder;
public function __construct()
{
$this->connector = new MySQL_Connector();
$this->builder = new SQLBuilder();
}
public function get_user_name()
{
$this->builder = $this->builder->clear()->select(['user_name'])->from('users');
$this->connector->execute($this->builder);
}
public function get_user()
{
$this->builder = $this->builder->clear()->from('users');
$this->connector->execute($this->builder);
}
}
echo " ------- \n";
$user = new User();
$user->get_user();
echo "\n ------- \n";
$user->get_user_name();
echo "\n ------- \n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.