powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [php] Фильтрация переменных в классе-обертке для БД
15 сообщений из 90, страница 4 из 4
[php] Фильтрация переменных в классе-обертке для БД
    #37793618
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: php
1.
2.
3.
if (!$this->link) {
                throw new Exception('No connection');
            }


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

Код: php
1.
2.
3.
4.
5.
// при создании создании объекта подключаемся
$db = new MySQL($conf);

// а при вызове метода open, выбирает другую базу, в SQLite другой файл откроет
$db->open('forum');
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793723
Edd.Dragon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Блин, да закройте эту тему! О чем она? Что тут обсуждается?
Флуд идет нескончаемой портянкой от автора...

Няша ррр
Еще раз - откройте для себя сайты для выкладывания своего кода! А тут тупо в ОДНОМ сообщении дайте туда ссылку. Или вообще вырежте из своей головы идею устраивать из sql.ru систему хранения исходников!

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

Код: php
1.
2.
3.
$stmt = $db->prepare("SELECT alias, title FROM :pages;");
$entries = $stmt->execute()->fetchPairs();
var_dump($entries);



Код: html
1.
2.
3.
4.
5.
6.
7.
8.
array(3) {
  ["test"]=>
  string(33) "Тестовая страница"
  ["new"]=>
  string(8) "New Page"
  ["contacts"]=>
  string(16) "Контакты"
}



Может кто чо подскажет, подкинет идею

Код: 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.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
<?php

abstract class DB_result {   
    protected $result;
    
    abstract public function fetch();
    
    abstract public function fetchNum();
    
    abstract public function fetchBoth();
    
    abstract public function fetchSingle();
    
    abstract public function fetchAll();
    
    abstract public function numRows();
    
    abstract public function seek($row = 0);
    
    abstract public function free();
        
    public function __construct($result) {
        $this->result = $result;
    }
    
    public function _destruct() {
        if ($this->result) {
            $this->free();
        }
    }
    
    public function fetchCol($column) {
        $type = is_int($column) ? 'NUM' : 'ASSOC';
        $records = $this->fetchAll($type);     
        $list = array();
        $count = count($records);
        
        if ($count) {
            if (!isset($records[0][$column])) {
                return false;
            }
            
            for ($row = 0; $row < $count; ++$row) {
                $list[] = $records[$row][$column];
            }
        }
        
        return $list;
    }
    
    public function fetchPairs() {
        $records = $this->fetchAll('NUM');     
        $pairs = array();
        $count = count($records);
        
        if ($count) {
            if (count($records[0]) < 2) {
                return false;
            }
            
            for ($row = 0; $row < $count; ++$row) {
                $pairs[$records[$row][0]] = $records[$row][1];
            }
        }
        
        return $pairs;
    }
}

?>

<?php

class MySQL_Result extends DB_Result {
    public function fetch() {
        return mysql_fetch_assoc($this->result);
    }
    
    public function fetchNum() {
        return mysql_fetch_row($this->result);
    }
    
    public function fetchBoth() {
        return mysql_fetch_array($this->result);
    }
    
    public function fetchSingle() {
        return mysql_result($this->result, 0);
    }
    
    public function fetchAll($type = 'ASSOC') {
        $type = strtoupper($type);
        $fetch_func = 'mysql_fetch_';
        
        switch ($type) {
            case 'NUM':
                $fetch_func .= 'row';
                break;
                
             case 'BOTH':
                $fetch_func .= 'array';
                break;
                 
             case 'ASSOC':
             default:
                 $fetch_func .= 'assoc';
        }
             
        $rows = array();
        
        while ($row = $fetch_func($this->result)) {
            $rows[] = $row;
        }
        
        return $rows;
    }
    
    public function numRows() {
        return mysql_num_rows($this->result);
    }
    
    public function seek($row = 0) {
        mysql_data_seek($this->result, $row);
    }
    
    public function free() {
        mysql_free_result($this->result);
        $this->result = null;
    }
}

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793747
Edd.Dragon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
автормне никто не мешает
Все-таки унылый тролль
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793750
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Хотя я думаю надо все эти намы, босы выкинуть и fetchCol и fetchPairs(переименовать в fetchAssoc) засунуть в класс MySQL_Result и переписать их с использованием нативных функций, хотя экономия на спичках, но всё же
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793776
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: php
1.
2.
3.
if (!$this->link) {
                throw new Exception('No connection');
            }


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


Код: php
1.
throw new Exception('MySQL Connection Error: ' . mysql_error($this->link));




Код: 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.
<?php

abstract class DB_Result {   
    protected $result;
    
    abstract public function fetch();
    
    abstract public function fetchSingle();
    
    abstract public function fetchAll();
    
    abstract public function fetchCol($column = 0);
    
    abstract public function fetchPairs();
    
    abstract public function seek($row = 0);
    
    abstract public function free();
        
    public function __construct($result) {
        $this->result = $result;
    }
    
    public function _destruct() {
        if ($this->result) {
            $this->free();
        }
    }
}

?>



Код: 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.
<?php

class MySQL_Result extends DB_Result {
    public function fetch() {
        return mysql_fetch_assoc($this->result);
    }
    
    public function fetchSingle() {
        return mysql_result($this->result, 0);
    }
    
    public function fetchAll() { 
        $rows = array();
        
        while ($row = mysql_fetch_assoc($this->result)) {
            $rows[] = $row;
        }
        
        return $rows;
    }
    
    public function fetchCol($column = 0) {
        $fetch_func = 'mysql_fetch_' . (is_int($column) ? 'row' : 'assoc');        
        $list = array();
        
        while ($row = $fetch_func($this->result)) {
            $list[] = $row[$column];
        }
        
        return $list;
    }
    
    public function fetchPairs() {    
        $pairs = array();
        
        while ($row = mysql_fetch_row($this->result)) {
            $array[$row[0]] = $row[1];
        }
        
        return $pairs;
    }
    
    public function numRows() {
        return mysql_num_rows($this->result);
    }
    
    public function seek($row = 0) {
        mysql_data_seek($this->result, $row);
    }
    
    public function free() {
        mysql_free_result($this->result);
        $this->result = null;
    }
}

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

Код: 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.
<?php

class MySQL extends DB {
    public function open($database = null) {
        if (!$this->link) {
            @$this->link = mysql_connect($this->conf['server'], $this->conf['username'], $this->conf['password']);
        
            if (!$this->link) {
                throw new Exception('No connection');
            }
        }
        
        if ($database) {
            $this->conf['database'] = $database;
        }
        
        if (!mysql_select_db($this->conf['database'], $this->link)) {
            throw new Exception('Database does not exist');
        }
    }
    
    public function close() {
        mysql_close($this->link);
        $this->link = null;
    }
    
    public function query($sql) {
        $result = mysql_query($sql, $this->link);
        
        if (is_resource($result)) {
            return new MySQL_Result($result);
        }
        
        if ($result === false) {
            throw new Exception('MySQL Error: ' . mysql_error($this->link) . '. Query: ' . $sql);
        }
    }
    
    public function escape($string) {
        return mysql_real_escape_string($string, $this->link);
    }
    
    public function affectedRows() {
        return mysql_affected_rows($this->link);
    }
    
    public function numRows() {
        return $this->affectedRows();
    }
    
    public function insertId() {
        return mysql_insert_id($this->link);
    }
}

?>



Код: 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.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
<?php

abstract class DB {
    protected $conf = array(
                  'database' => null, 
                  'prefix' => null
               ), 
               $link, 
               $temp;
    
    abstract public function open($database = null);
    
    abstract public function close();
    
    abstract public function query($sql);
    
    abstract public function escape($string);
    
    abstract public function insertId();
    
    abstract public function affectedRows();
    
    abstract public function numRows();
    
    public function __construct(array $conf) {
        $conf = array_change_key_case($conf);
        $this->conf = array_merge($this->conf, $conf);
        $this->open();
    }
    
    public function __destruct() {
        $this->close();
    }
    
    public function getConf() {
        return $this->conf;
    }
    
    public function table($name) {
        return $this->conf['prefix'] . $name; 
    }
    
    public function setCharset($charset) {
        $this->query("SET NAMES $charset;");
    }
    
    public function quote($string) {
        return "'" . $this->escape($string) . "'";
    }
    
    public function raw($string) {
        return new DB_Expression($string);
    }
    
    public function filterArray($array) {
        foreach ($array as &$value) {
            if (is_null($value)) {
                $value = 'NULL';
            }
            else if (is_bool($value)) {
                $value = $value ? 'TRUE' : 'FALSE';
            }
            else if (is_string($value)) {
                $value = $this->quote($value);
            }
        }
        
        return $array;
    }
    
    public function valueList($values) {
        $values = $this->filterArray($values);
        $str = implode(', ', $values);
        return $str;
    }
    
    public function fieldList($fields) {
        $array = $this->filterArray($fields);      
        $str = '';
        
        foreach ($fields as $key => $value) {
            $str .= $key . ' = ' . $value . ', ';
        }
        
        $str = substr($str, 0, -2);
        return $str;
    }
    
    protected function replaceHolders($matches) {
        if ($matches[1]) {
            return $this->table($matches[1]);
        }
        else {
            $value = $matches[2] ? $this->temp[$matches[2]] : next($this->temp);
            
            switch ($matches[3]) {
                case '':
                case 's':
                    return $this->quote($value);
                    
                case 'i':
                case 'd':
                    return intval($value);
                    
                case 'j':
                    return implode(', ', $value);

                case 'v':
                    return $this->valueList($value);

                case 'f':
                    return $this->fieldList($value);
                    
                default:
                    throw new Exception("Unknown placeholder ?{$matches[3]}");
            }
        }
    }
    
    /**
     * Производит поиск и замену в SQL-строке плейсхолдеров, возвращает объект DB_Statement.
     *
     * $login = 'tester';
     * $password = 'test';
     * $stmt = $db->prepare('SELECT * FROM :users WHERE login = 2? AND password = 1?s;', $password, $login);
     * {номер_аргумента}?{флаг}
     * :      -> добавит преффикс к таблице
     * ?, ?s  -> экранированная строка в кавычках
     * ?i, ?d -> число
     * ?j     -> значения через запятую без фильтрации
     * ?v     -> значения через запятую c фильтрацие
     * ?f     -> поле = значение, ... с фильтрацией
     */
    public function prepare() {
        $this->temp = func_get_args();
        $pattern = '/:(\w+)|(\d*)\?([a-z]?)/s';
        $callback = array($this, 'replaceHolders');
        $sql = preg_replace_callback($pattern, $callback, $this->temp[0]);
        $stmt = new DB_Statement($this, $sql);
        return $stmt;
    }
    
    public function find($table, $id, $columns = '*') {
        $table = $this->table($table);
        $id = (int) $id;
        $result = $db->query("SELECT $columns FROM $table WHERE id = $id;");
    }
    
    public function insert($table, $row, $return_insert_id = true) {
        $table = $this->table($table);
        $columns = implode(', ', array_keys($row));
        $values = $this->valueList($row);
        $this->query("INSERT INTO $table ($columns) VALUES ($values);");
        
        if ($return_insert_id) {
            return $this->insertId();
        }
    }

    public function update($table, $fields, $id) {
        $table = $this->table($table);
        $set = $this->fieldList($fields);
        $id = (int) $id;
        $this->query("UPDATE $table SET $set WHERE id = $id;");
    }

    public function delete($table, $id) {
        $table = $this->table($table);
        $id = (int) $id;
        $this->query("DELETE FROM $table WHERE id = $id;");
    }
    
    public function count($table, $extra = 1) {
        $table = $this->table($table);
        $result = $this->query("SELECT COUNT(*) FROM $table WHERE $extra;");
        $num = (int) $result->fetchSingle();
        return $num;
    }
}

?>




Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<?php

class DB_Expression {
    private $value;
    
    public function __construct($value) {
        $this->value = $value;
    }
    
    public function __toString() {
        return $this->value;
    }
}

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793788
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
<?php

class DB_Statement {
    private $db, $sql;
    
    public function __construct($db, $sql) {
        $this->db = $db;
        $this->sql = $sql;
    }
    
    public function execute() {
        return $this->db->query($this->sql);
    }
    
    public function __toString() {
        return $this->sql;
    }
}

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793804
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Класс DB_Expression применяется для создания хука при фильтрации. При использовании $db->insert($table, $fields) все значения полей фильтруются, а строки эскейпется. Обходится так:

Код: php
1.
2.
$entry['published'] = $db->raw('CURRENT_TIMESTAMP');
$db->insert('news', $entry);



DB_Statement используется для сокращения кода:

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
$stmt = $db->prepare("SELECT alias, title FROM :pages;");
$entries = $stmt->execute()->fetchPairs();

// Хотя и так можно
$sql = $db->prepare("SELECT alias, title FROM :pages;");
$entries = $db->query($sql)->fetchPairs(); // правда ф-ии query надо модифицировать

    public function query($sql) {
        $result = mysql_query($sql, $this->link);
        
        if (is_resource($result)) {
            return new MySQL_Result($result);
        }
        
        if ($result === false) {
            throw new Exception('MySQL Error: ' . mysql_error($this->link) . '. Query: ' . $sql);
        }
        
        return $this;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793808
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
bootstrap.php

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<?php

function __autoload($class) {
    $path = __DIR__ . '/classes/' . strtolower($class) . '.php';
    if (file_exists($path)) {
        require_once($path);
    }
    else {
        throw new Exception("Class $class not found.");
    }
}

mb_internal_encoding('utf-8');

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793813
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Имя_класса.php в папку lib/classes и можно проверять

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
<?php

require_once('lib/bootstrap.php');

$conf['server'] = 'localhost';
$conf['username'] = 'Пользователь';
$conf['password'] = 'Пароль';
$conf['database'] = 'Имя базы';
$conf['prefix'] = 'prefix_';

$db = new MySQL($conf);
$db->setCharset('utf8');

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793831
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
    public function fetchPairs() {    
        $pairs = array();
        
        while ($row = mysql_fetch_row($this->result)) {
            $pairs[$row[0]] = $row[1];
        }
        
        return $pairs;
    }



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


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