powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [php] Фильтрация переменных в классе-обертке для БД
25 сообщений из 90, страница 2 из 4
[php] Фильтрация переменных в классе-обертке для БД
    #37790977
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
    private function _replacePlaceHolders($matches) {
        if ($matches[1]) {
            return $this->getTablename($matches[1]);
        }
        else {
            $value = $matches[2] ? $this->_args[$matches[2]] : next($this->_args);
            
            switch ($matches[3]) {
                case '':
                case 's':
                    return $this->quote($value);
                    
                case 'i':
                case 'd':
                    return intval($value);
                    
                case 'a': 
                    return implode(', ', $value);

                case 'ai': // Indexed Array
                    return $this->_list($value);

                case 'as': // Associative Array
                    return $this->_set($value);
                    
                default:
                    throw new Exception("Unknown placeholder ?{$matches[3]}.");
            }
        }
    }
    
    private function _prepare($args = null) {
        if ($args) {
            $this->_args = $args;
        }
        
        if (count($this->_args) > 1) {
            $pattern = '/:([a-z]+)|([1-9]+[0-9]*)?\?([a-z]*)/is';
            return preg_replace_callback($pattern, array($this, '_replacePlaceHolders'), $this->_args[0]);
        }
        else {
            return $this->_args[0];
        }
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791214
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Няша ррр,

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
<?php

/**
 * Абстрактный слой для работы с базой данных.
 * 
 * Возможности:
 *... Поддержка плейсхолдеров.<br>
 *....... Типы плейсхолдеров<br>
 *........... :tablename       -> добавляем префикс к имени таблицы<br>
 *........... {arg_num}?{flag} -> заменяет на значение<br>
 *........... Подробнее см. справку к методу prepare.<br><br>
 *........Синтаксис.<br>
 *........... $dbo->$method($formatted_sql[, $arg1[, $arg2[, $_args]]]);<br><br>
 *....... Методы с поддержкой:<br>
 *........... prepare, query, row, rows, one<br><br>
 *... Автоматизация рутинных операций, таких как: несложная выборка, INSERT, UPDATE, DELETE.<br>
 *... Безопасное добавление и обновление данных(insert, update).<br>
 *....... Если нужно передать в методы insert, update строку как есть, то нужно для этого нужно использовать метод unescape:<br><br>
 *........... $entry['published'] = $db->unescape('DATETIME');<br>
 *........... $db->insert('news', $entry);
 * 
 */
abstract class DB {
    protected $_args, $_connection;   
    public $tablesPrefix,
           $counter = 0,
           $lastQuery,
           $executionTime,
           $totalExecutionTime = 0,
           $affectedRows = 0,
           $numRows;
    
    abstract protected function _query($sql);
    
    abstract protected function _error();
    
    abstract protected function _errNo();
    
    abstract protected function _affectedRows();
    
    abstract public function insertId();
    
    abstract public function escape($string);
    
    abstract public function fetch($result);
    
    abstract public function single($result, $row, $field);
    
    abstract public function seek($result, $row);
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791243
Фотография Ренат
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Няша ррр,

иногда страное чуство дежавю green_troll`я...
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791297
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Ренат, какие ещё идеи есть?
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791328
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
этак скоро мыдо формальной грамматики дойдем.
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791414
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
    public function query() {
        $this->_args = func_get_args();
        $sql = $this->_prepare();
        return $this->rawQuery($sql);
    }
    
    /**
     * Отправляет запрос, возвращает количество модифицированных рядов.
     */
    public function execute($sql) {
        $this->_args = func_get_args();
        $sql = $this->_prepare();
        $this->rawQuery($sql);
        return $this->affectedRows;
    }

    /**
     * В случае удачи возвращает один ряд в виде ассоциативного массива либо false.
     * 
     * @param string $sql SQL-строка
     * @return mixed 
     */
    public function row() {
        $this->_args = func_get_args();
        $sql = $this->_prepare();
        $result = $this->rawQuery($sql);
        return $this->fetch($result);
    }
    
    /**
     * В случае удачи возвращает двухмерный массив либо пустой массив.
     * 
     * @param string $sql SQL-строка
     * @return mixed 
     */
    public function rows($sql) {
        $this->_args = func_get_args();
        $sql = $this->_prepare();
        $result = $this->rawQuery($sql);
        return $this->fetchAll($result);
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791773
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Няша ррр,

Вставляем 1000 новостей.

Код: php
1.
2.
3.
4.
5.
6.
$i = 0;
while ($i++ < 1000) {
    $entry['id'] = null;
    $entry['title'] = 'Новость#' . $i;
    $db->insert('news', $entry, false);
}



Простая реализация постраничной навигации.

Код: php
1.
2.
3.
4.
5.
6.
7.
$page = isset($_GET['page']) ? $_GET['page'] : null;

$entries = $db->getAll('news', array('limit' => 10, 'page' => $page));

echo '<pre>';
var_dump($entries);
echo '</pre>';



Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
    public function select($table, $options = array()) {
        $defaults = array(
            'columns' => '*',
            'where' => null,
            'order' => null,
            'offset' => null,
            'limit' => null,
            'page' => 0,
        );
        
        if ($options) {
            $options = array_change_key_case($options);  
        }
        
        $options = array_merge($defaults, $options);
        
        $sql = "SELECT {$options['columns']}";      
        $sql .= ' FROM ' . $this->table($table);
        
        if ($options['where']) {
            $sql .= " WHERE {$options['where']}";
        }
        
        if ($options['order']) {
            $sql .= " ORDER BY {$options['order']}";
        }
        
        if (!is_null($options['offset']) || !is_null($options['limit'])) {                      
            $limit = intval($options['limit']);
            $offset = $options['page'] > 0 ? $options['page'] * $limit - $limit :  intval($options['offset']);
            $sql .= " LIMIT $offset, $limit";
        }
        
        $sql .= ';';
        $result = $this->query($sql);
        return $result;
    }

    public function get($table, $options = array()) {
        $result = $this->select($table, $options);
        return $this->fetch($result);
    }
    
    public function find($table, $id, $columns = '*') {
        return $this->get($table, array('columns' => $columns, 'where' => 'id = ' . intval($id)));
    }
    
    public function getAll($table, $options = array()) {
        $result = $this->select($table, $options); 
        return $this->fetchAll($result);
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791793
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Хм

Код: php
1.
2.
var_dump(' 1 
    ' > 0); // bool(true)
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791796
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
    public function select($table, $options = array()) {
        $defaults = array(
            'columns' => '*',
            'where' => '',
            'order' => '',
            'limit' => 0,
            'page' => 0,
        );
        
        if ($options) {
            $options = array_change_key_case($options);  
        }
        
        $options = array_merge($defaults, $options);
        
        $sql = "SELECT {$options['columns']}";      
        $sql .= ' FROM ' . $this->table($table);
        
        if ($options['where']) {
            $sql .= " WHERE {$options['where']}";
        }
        
        if ($options['order']) {
            $sql .= " ORDER BY {$options['order']}";
        }
        
        if ($options['limit'] > 0) {                      
            $limit = intval($options['limit']);
            $offset = $options['page'] > 0 ? $options['page'] * $limit - $limit :  0;
            $sql .= " LIMIT $offset, $limit";
        }
        
        $sql .= ';';
        $result = $this->query($sql);
        return $result;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791808
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
var_dump($db->get('pages', array('where' => $db->like('title', 'Тест'), 'limit' => 1)));
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791813
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
   public function like($column, $string) {
        $string = $this->escape($string);
        $search = array('%', '_');
        $replacements = array('\%', '\_');
        $string = str_replace($search, $replacements, $string);   
        return "$column LIKE '%$string%'";
    } 
    
    public function search($columns, $string) {  
        return "MATCH($columns) AGAINST (" . $this->quote($string) . ")";
    }



С сцеплением плохая идея, да и плодить сущности без необходимости незачем
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791816
vkle
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Топик постепенно становится похожим то ли на личный веб-лог автора, то ли на хауту от какой-то софтины-на-все-случаи-жизни. Уже хочется поскорее скачать и посмотреть, реализованы ли в текущей версии счетчики количества запросов и времени их выполнения, возможность сброса в лог... для отладки штука полезная. Мдя, не припоминаю, чтоб на форуме разрешалось вести личный блог.
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791844
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
vkle,

Класс MySQL выглядит так:

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
<?php

class MySQL extends DB {
    public function __construct($db_host, $db_user, $db_pass, $db_name, $tables_prefix = null) {
        $this->tablesPrefix = $tables_prefix;
        
        @$this->_connection = mysql_connect($db_host, $db_user, $db_pass);
        if (!$this->_connection) {
            throw new Exception('Can\'t connect to MySQL server.');
        }
        if (!mysql_select_db($db_name, $this->_connection)) {
            throw new Exception('Database does not exist.');
        } 
    }
    
    protected function _query($sql) {
        return mysql_query($sql, $this->_connection);   
    }
    
    protected function _affectedRows() {
        return mysql_affected_rows($this->_connection);
    }
    
    public function error() {
        return mysql_error($this->_connection);
    }
    
    public function errno() {
        return mysql_errno($this->_connection);
    }
    
    public function insertId() {
        return mysql_insert_id($this->_connection);
    }

    public function escape($string) {
        return mysql_real_escape_string($string, $this->_connection);
    }

    public function fetch($result) {
        return mysql_fetch_assoc($result);
    }

    public function seek($result, $row = 0) {
        return mysql_data_seek($result, $row);
    }

    public function __destruct() {
        return mysql_close($this->_connection);
    }
}

?>



Так что чтобы реализовать, враппер для MySQLi особых сложностей не составит.

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
  /**
     * Отправляет 'сырой' запрос.
     */  
    public function query($sql) {
        ++$this->counter;
        $this->lastQuery = $sql;
        $this->executionTime = -microtime(1);
        $result = $this->_query($sql);
        $this->executionTime += microtime(1);
        $this->totalExecutionTime += $this->executionTime;
        $this->numRows = null;
        $this->affectedRows = $this->_affectedRows();
        
        if (!is_bool($result)) {
            $this->numRows = $this->affectedRows;   
            return $result;
        }
        else if (!$result) {
            throw new Exception('SQL Error Code: ' . $this->errno() . ' - ' . $this->error() . '. Query: "' . $sql .'".');
        } 
    }



Да все замеряется.

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
   public function pquery() {
        $this->_args = func_get_args();
        $sql = $this->_prepareSql();
        return $this->query($sql);
    }
    
    public function fetchOne($result) {
        $row = $this->fetch($result);
        
        if (is_array($row)) {
            return current($row);
        }
        
        return false;
    }
    
    /**
     * Вернет одно значение, либо false
     **/
    public function one() {
        $this->_args = func_get_args();
        $sql = $this->_prepareSql();
        $result = $this->query($sql);
        return $this->fetchOne($result);
    }

    /**
     * В случае удачи возвращает один ряд в виде ассоциативного массива либо false.
     */
    public function row() {
        $this->_args = func_get_args();
        $sql = $this->_prepareSql();
        $result = $this->query($sql);
        return $this->fetch($result);
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791846
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
  /**
     * Посчитать количество рядов в таблице.
     */
    public function count($table, $column, $where = null) {
        $value = $this->single($table, "COUNT($column)", $where);    
        
        if ($value === false) {
            return false;
        }
        
        return intval($value);
    }
    
    /**
     * Посчитать количество всех рядов в таблице.
     */
    public function countAll($table, $where = null) {
        return $this->count($table, '*', $where);
    }
    
    public function countPages($table, $limit, $where = null) {
        if ($limit > 0) {
            $total = $this->countAll($table, $where);
            
            if ($total === false) {
                return false;
            }
            
            return ceil($total / $limit);
        }
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791850
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Наврядли освобождение предыдущего результата даст что-то

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
    public function query($sql) {     
        ++$this->counter;
        $this->lastQuery = $sql;
        $this->executionTime = -microtime(1);
        $result = $this->_query($sql);
        
        if ($this->lastResult) {
            $this->freeResult($this->lastResult);
        }
        
        $lastResult = $result;
        $this->executionTime += microtime(1);
        $this->totalExecutionTime += $this->executionTime;
        $this->numRows = null;
        $this->affectedRows = $this->_affectedRows();
        
        if (!is_bool($result)) {
            $this->numRows = $this->affectedRows;   
            return $result;
        }
        else if (!$result) {
            throw new Exception('SQL Error Code: ' . $this->errno() . ' - ' . $this->error() . '. Query: "' . $sql .'".');
        } 
    }

    // ...
    
    public function __destruct() {
        if ($this->lastResult) {
            $this->freeResult($this->lastResult);
        }
    
        $this->close();
    }  
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791861
Фотография r u
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vkle,

это новый вид бота
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37791990
Фотография Hett
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
r uvkle,

это новый вид бота
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792035
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Hett,

Так всё переделал, теперь указатель на результат хранится в самом объекте

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
$db->select('news', array('limit' => 10, 'page' => 5));
$news = $db->fetchAll();

/*
Можно и так писать:

$news = $db->getAll('news', array('limit' => 10, 'page' => 5));

Но это для наглядности.
*/
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792058
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Няша ррр,

Всё-таки сделал сцепление(chain вроде ж цепь, хз как по-русски) для методов query, pquery(prepared query, метод с поддержкой плейсхолдеров), select, они все равно ничего не возвращали

Код: php
1.
2.
3.
echo '<pre>';
var_dump($db->select('pages', array('where' => $db->like('title', 'Тест'), 'limit' => 1))->fetchAll());
echo '</pre>';



Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
<pre>array(1) {
  [0]=>
  array(6) {
    ["id"]=>
    string(1) "1"
    ["alias"]=>
    string(4) "test"
    ["title"]=>
    string(33) "Тестовая страница"
    ["keywords"]=>
    string(0) ""
    ["description"]=>
    string(0) ""
    ["content"]=>
    string(18) "<p>It's works!</p>"
  }
}
</pre>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792079
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
<?php

class MySQL extends DB {
    public function __construct($db_host, $db_user, $db_pass, $db_name) {
        @$this->_connection = mysql_connect($db_host, $db_user, $db_pass);
        if (!$this->_connection) {
            throw new Exception('Can\'t connect to MySQL server.');
        }
        if (!mysql_select_db($db_name, $this->_connection)) {
            throw new Exception('Database does not exist.');
        } 
    }
    
    protected function _query($sql) {
        return mysql_query($sql, $this->_connection);   
    }
    
    public function affectedRows() {
        return mysql_affected_rows($this->_connection);
    }
    
    public function error() {
        return mysql_error($this->_connection);
    }
    
    public function errno() {
        return mysql_errno($this->_connection);
    }
    
    public function insertId() {
        return mysql_insert_id($this->_connection);
    }

    public function escape($string) {
        return mysql_real_escape_string($string, $this->_connection);
    }

    public function fetchAssoc() {
        return mysql_fetch_assoc($this->_result);
    }
    
    public function fetchNum() {
        return mysql_fetch_row($this->_result);
    }
    
    public function fetchArray() {
        return mysql_fetch_array($this->_result);
    }
    
    public function freeResult() {
        return mysql_free_result($this->_result);
    }

    public function seek($row = 0) {
        return mysql_data_seek($this->_result, $row);
    }

    public function close() {
        return mysql_close($this->_connection);
    }
}

?>



Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
    public function fetch($type = 'ASSOC') {
        $type = strtoupper($type);
        
        switch ($type) {
            case 'ASSOC':
                return $this->fetchAssoc();
                
            case 'NUM':
                return $this->fetchNum();
                
            case 'BOTH':
                return $this->fetchArray();
            
            case 'OBJECT':
                return (object) $this->fetchAssoc();
                
            default:
                throw new Exception("Unknown fetch type {$type}.");
        }
    }
    
    public function fetchAll($type = 'ASSOC') {
        $rows = array();
        
        while ($row = $this->fetch($type)) {
            $rows[] = $row;
        }
        
        return $rows;
    } 
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792084
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Няша ррр,

Код: php
1.
2.
3.
    public function fetchObject($class_name = null, $params = array()) {
        return mysql_fetch_object($this->_result, $class_name, $params);
    }




Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
class Page {
    private $_db;
    
    public function __construct($db) {
        $this->_db = $db;
    }
    
    public function save() {
        // $this->_db->update ...
    }
}

$page = $db->select('pages', array('where' => $db->like('title', 'Тест'), 'limit' => 1))->fetchObject('Page', array($db));

echo '<pre>';
var_dump($page);
echo '</pre>';



Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
<pre>object(Page)#2 (7) {
  ["_db":"Page":private]=>
  object(MySQL)#1 (10) {
    ["_connection":protected]=>
    resource(9) of type (mysql link)
    ["_result":protected]=>
    resource(10) of type (mysql result)
    ["_args":protected]=>
    NULL
    ["tablesPrefix"]=>
    string(2) "t_"
    ["counter"]=>
    int(2)
    ["lastQuery"]=>
    string(63) "SELECT * FROM t_pages WHERE title LIKE '%Тест%' LIMIT 0, 1;"
    ["executionTime"]=>
    float(0.00045084953308105)
    ["totalExecutionTime"]=>
    float(0.00087785720825195)
    ["affectedRows"]=>
    int(1)
    ["numRows"]=>
    int(1)
  }
  ["id"]=>
  string(1) "1"
  ["alias"]=>
  string(4) "test"
  ["title"]=>
  string(33) "Тестовая страница"
  ["keywords"]=>
  string(0) ""
  ["description"]=>
  string(0) ""
  ["content"]=>
  string(18) "<p>It's works!</p>"
}
</pre>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792086
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
    public function fetch($type = 'ASSOC') {
        $type = strtoupper($type);
        
        switch ($type) {
            case 'ASSOC':
                return $this->fetchAssoc();
                
            case 'NUM':
                return $this->fetchNum();
                
            case 'BOTH':
                return $this->fetchArray();
                
            default:
                throw new Exception("Unknown fetch type {$type}.");
        }
    }
    
    public function fetchAll($type = 'ASSOC') {
        $rows = array();
        
        while ($row = $this->fetch($type)) {
            $rows[] = $row;
        }
        
        return $rows;
    } 
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792137
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Такого нигде не видел.

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
function show_entry($entry) {
?>
<h2><?=$entry['title']?></h2>
<p><?=$entry['description']?></p>
Опубликовано: <?=$entry['published']?>. <a href="news/<?=$entry['id']?>">Читать полностью &raquo;</a>
<?php
}

$page = isset($_GET['page']) ? $_GET['page'] : null;
$db->select('news', array('columns' => 'id, title, description, published', 'limit' => 10, 'page' => $page, 'order' => 'id DESC'));
$db->fetchCallback('show_entry');



Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
<h2>Новость #50</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/50">Читать полностью &raquo;</a>
<h2>Новость #49</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/49">Читать полностью &raquo;</a>
<h2>Новость #48</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/48">Читать полностью &raquo;</a>
<h2>Новость #47</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/47">Читать полностью &raquo;</a>
<h2>Новость #46</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/46">Читать полностью &raquo;</a>
<h2>Новость #45</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/45">Читать полностью &raquo;</a>
<h2>Новость #44</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/44">Читать полностью &raquo;</a>
<h2>Новость #43</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/43">Читать полностью &raquo;</a>
<h2>Новость #42</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/42">Читать полностью &raquo;</a>
<h2>Новость #41</h2>
<p>Кратко</p>
Опубликовано: 2012-05-13 15:52:33. <a href="news/41">Читать полностью &raquo;</a>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792156
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
И даже так:

Код: php
1.
2.
$db->prepare('UPDATE :news SET description = ?;', 'Без описания')->query();
echo $db->sql; // хотя пожалуй я сделаю его protected



$db->pquery($formatted_sql, $_args); // return $this

заменяет

$db->prepare($formatted_sql, $_args); // return $this
$db->query(null); // return $this, т.е. можно строит такие цепочки $db->prepare()->query()->fetch();

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
    /**
     * Отправляет 'сырой' запрос, либо подготовленный.
     */  
    public function query($sql = null) {     
        if ($sql) {
            $this->sql = $sql;
        }
        
        if (is_resource($this->_result)) { // освобождаем предыдущий результат
            $this->freeResult();
        }
        
        ++$this->counter;
        $this->executionTime = -microtime(1);
        $this->_result = $this->_query($this->sql);       
        $this->executionTime += microtime(1);
        $this->totalExecutionTime += $this->executionTime;
        $this->numRows = null;
        $this->affectedRows = $this->affectedRows();
        
        if (!is_bool($this->_result)) {
            $this->numRows = $this->affectedRows;   
        }
        else if (!$this->_result) {
            throw new Exception('SQL Error Code: ' . $this->errno() . ' - ' . $this->error() . '. Query: "' . $sql .'".');
        } 
        return $this;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792157
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Няша ррр
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
    public function fetch($type = 'ASSOC') {
        $type = strtoupper($type);
        
        switch ($type) {
            case 'ASSOC':
                return $this->fetchAssoc();
                
            case 'NUM':
                return $this->fetchNum();
                
            case 'BOTH':
                return $this->fetchArray();
                
            default:
                throw new Exception("Unknown fetch type {$type}.");
        }
    }
    
    public function fetchAll($type = 'ASSOC') {
        $rows = array();
        
        while ($row = $this->fetch($type)) {
            $rows[] = $row;
        }
        
        return $rows;
    } 




редкосnysq бред.
...
Рейтинг: 0 / 0
25 сообщений из 90, страница 2 из 4
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [php] Фильтрация переменных в классе-обертке для БД
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]