SQLBuilder (постоитель запросов)
- class SQLBuilder {
- private $sql;
- private $table;
- private $fieldTypes = array(
- 'v' => 'varchar(255) NOT NULL',
- 'i' => 'int(11) NOT NULL',
- 't' => 'text NOT NULL'
- );
- public function __construct($table) {
- $this->table = $table; // set table
- }
- public function getSQL() {
- return $this->sql;
- }
- public function getTable() {
- return $this->table;
- }
- public function type($key) {
- return $this->fieldTypes[$key];
- }
- public function createTable($args) {
- $sql = array();
- $sql[] = 'CREATE TABLE IF NOT EXISTS `' . $this->getTable() . '` (
- `id` int(11) NOT NULL AUTO_INCREMENT';
- foreach ($args as $name => $type) {
- $sql[] = '`' . $name . '` ' . $this->type($type);
- }
- $sql[] = 'PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;';
- $this->sql = implode(', ', $sql); // join()
- return $this;
- }
- public function delete($id) {
- $this->sql = 'DELETE `' . $this->table . '` WHERE `id` = ' . intval($id);
- return $this;
- }
- public function insert($values, $fields = false) {
- $this->sql = "INSERT INTO `" . $this->table . "` " . ($fields ? "(`" . implode("`, `", $fields) . "`)" : '') . " VALUES('" . implode("', '", $values) . "')";
- return $this;
- }
- public function update($values, $id) {
- $sql = array();
- $parts = array();
- $this->sql = 'UPDATE `' . $this->table . '` SET ';
- foreach($values as $field => $value) {
- $parts[] = "`" . $field . "` = '" . $value . "'";
- }
- $sql[] = sizeof($parts) > 1 ? implode(', ', $parts) : $parts[0];
- $this->sql .= implode(', ', $sql);
- $this->sql .= ' WHERE `id` = ' . intval($id);
- return $this;
- }
- }
функционал не весь, навелосипедил))
пример
пример
- $obj = new SQLbuilder('users');
- $args = array(
- 'name' => 'v',
- 'age' => 'i',
- 'text' => 't'
- );
- echo 'CREATE -> ' . $obj->createTable($args)->getSQL();
- echo '<br />';
- $fields = array('name', 'age');
- $values = array('vasya', 22);
- echo 'INSERT with fields -> ' . $obj->insert($values, $fields)->getSQL();
- echo '<br />';
- $values2 = array(null, 'vasya', 22, 'test text');
- echo 'INSERT without fields -> ' . $obj->insert($values2)->getSQL();
- echo '<br />';
- $id = 2;
- $values = array('name' => 'Petya', 'age' => 23);
- echo 'UPDATE -> ' . $obj->update($values, $id)->getSQL();