powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [php] Фильтрация переменных в классе-обертке для БД
25 сообщений из 90, страница 3 из 4
[php] Фильтрация переменных в классе-обертке для БД
    #37792158
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
вам что за количество строк кода платят?
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792186
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
ScareCrow, почему?
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792187
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
в мод иксе или джумле такое видел
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792198
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: 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.
<?php

class MySQL extends DB {
    protected function _open() {       
        @$this->_connection = mysql_connect($this->_conf['server'], $this->_conf['user'], $this->_conf['password']);
        if (!$this->_connection) {
            throw new Exception('Can\'t connect to MySQL server.');
        }
        if (!mysql_select_db($this->_conf['database'], $this->_connection)) {
            throw new Exception('Database does not exist.');
        }
    }
    
    protected function _close() {
        return mysql_close($this->_connection);
    }
    
    protected function _query($sql) {
        return mysql_query($sql, $this->_connection);   
    }
    
    public function affectedRows() {
        return mysql_affected_rows($this->_connection);
    }
    
    public function numRows() {
        return $this->affectedRows();
    }
    
    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() {
        return mysql_fetch_assoc($this->_result);
    }
    
    public function freeResult() {
        return mysql_free_result($this->_result);
    }

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

?>



<?php

/**
* Абстрактный слой для работы с базой данных.
*
* Возможности:
* Поддержка плейсхолдеров.
* Типы плейсхолдеров.
* :tablename -> добавляем префикс к имени таблицы.
* {arg_num}?{flag} -> заменяет на значение.
* Подробнее см справку к методу prepare.
*
* Синтаксис.
* $dbo->{$method}($formatted_sql[, $arg1[, $arg2[, $_args]]]);
*
* Методы с полной поддержкой плейсхолдеров:
* prepare, pquery, one, row, rows
*
* Автоматизация рутинных операций, таких как: несложная выборка, INSERT, UPDATE, DELETE.
* Безопасное добавление и обновление данных(insert, update).
* Если нужно передать в методы insert, update строку как есть, то нужно для использовать метод raw:
* $entry['published'] = $db->raw('DATETIME');
* $db->insert('news', $entry);
*
*/
abstract class DB {
protected $_conf = array('prefix' => ''),
$_connection,
$_sql,
$_result,
$_args,
$_statistics = array('Queries' => 0, 'Execution Time' => 0, 'Total Execution Time' => 0);

abstract protected function _open();

abstract protected function _close();

abstract protected function _query($sql);

abstract public function fetch();

abstract public function numRows();

abstract public function affectedRows();

abstract public function error();

abstract public function errno();

abstract public function insertId();

abstract public function escape($string);

abstract public function freeResult();

abstract public function seek($row);

public function __construct($conf) {
$conf = array_change_key_case($conf);
$defaults = array('prefix' => '');
$conf = array_merge($defaults, $conf);
$this->_conf = $conf;
$this->_open();
}

public function getConf() {
return $this->_conf;
}

public function getSql() {
return $this->_sql;
}

public function getStatistics() {
return $this->_statistics;
}

public function table($name) {
return $this->_conf['prefix'] . $name;
}

/**
* Отправляет 'сырой' запрос, либо подготовленный.
*/
public function query($sql = null) {
if ($sql) {
$this->_sql = $sql;
}

if (is_resource($this->_result)) { // освобождаем предыдущий результат
$this->freeResult();
}

$this->_statistics['Queries'] += 1;
$this->_statistics['Execution Time'] = -microtime(1);
$this->_result = $this->_query($this->_sql);
$this->_statistics['Execution Time'] += microtime(1);
$this->_statistics['Total Execution Time'] += $this->_statistics['Execution Time'];

if (is_bool($this->_result) && !$this->_result) {
throw new Exception('SQL Error Code: ' . $this->errno() . ' - ' . $this->error() . '. Query: "' . $sql .'".');
}

return $this;
}

public function setCharset($charset) {
$this->query("SET NAMES $charset;");
}

public function fetchAll() {
$rows = array();

while ($row = $this->fetch()) {
$rows[] = $row;
}

return $rows;
}

Код: php
1.
2.
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792200
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
    public function __construct($conf) {
        $conf = array_change_key_case($conf);
        $this->_conf = array_merge($this->_conf, $conf);
        $this->_open();
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792222
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: php
1.
2.
3.
4.
5.
6.
7.
public function error() {
        return mysql_error($this->_connection);
    }
    
    public function errno() {
        return mysql_errno($this->_connection);
    }


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

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

$page = isset($_GET['page']) ? $_GET['page'] : null;

$buff = $db->select('news', 
            array(
                'columns' => 'id, title, description, published', 
                'limit' => 10, 
                'page' => $page, 
                'order' => 'id DESC'
            ))->fetchRender('show_entry');

echo $buff;



Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
    public function fetchRender($callback) {
        $buff = '';
        
        while ($row = $this->fetch()) {
            $buff .= call_user_func($callback, $row);
        }
        
        return $buff;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792240
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
обработки ошибок нету
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792263
авторобработки ошибок нету
гыгыгы !

to Няша ррр
MVC pattern уже изобретён - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Код: 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.
<?php
namespace abstracts;

    abstract class ModelPDO
    {        
        protected $conn = NULL;
        protected $stmt = NULL;

        public function __construct( $connection_string )
        {
            try
            {
                $this->conn = new \PDO( $connection_string );
            }
            catch( \PDOException $ex )
            {
                die( $ex->getMessage() );
            }           
        }

	public function __destruct()
	{
	    if( $this->conn ) $this->conn = NULL;
            if( $this->stmt ) $this->stmt = NULL;
	}
}
?>


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

namespace models;

class gallerySqlite extends \abstracts\ModelPDO {

    public function __construct() {
        parent::__construct('sqlite:app_data/gallery.sqlite');
    }

    public function getPictures() {

        $query = 'SELECT id,
                      description,
                      short_description
                  FROM pictures;';

        $this->stmt = $this->conn->prepare($query);
        $this->stmt->execute();

        return $this->stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function getPictureById($id) {

        $query = 'SELECT body,
                     type,
                     size
                  FROM pictures
                  WHERE id = :id;';

        $this->stmt = $this->conn->prepare($query);
        $this->stmt->execute(array((int) $id));

        return $this->stmt->fetch(\PDO::FETCH_ASSOC);
    }

    public function getModifedById($id) {

        $query = 'SELECT modifed
                  FROM pictures
                  WHERE id = :id;';

        $this->stmt = $this->conn->prepare($query);
        $this->stmt->execute(array((int) $id));

        return $this->stmt->fetchColumn();
    }

    public function insertNew(array $picture) {

        \my_validator::getInstance()
                ->isEmpty($_name = & $picture['name'], 'file')
                ->isLonger($_name, NULL, 150)
                ->isEmpty($_type = & $picture['type'])
                ->inArray($_type, NULL, array(
                                            'image/gif',
                                            'image/jpeg',
                                            'image/pjpeg',
                                            'image/png'
                                        ))
                ->isInt($_size = & $picture['size'])
                ->isLarger($_size, NULL, 153600)
                ->isEmpty($_error = & $picture['error'])
                ->isEmpty($_tmp_name = & $picture['tmp_name'])
                ->isEmpty($_description = & $picture['description'], 'description')
                ->isLonger($_description, NULL, 250)
                ->isEmpty($_short_description = & $picture['short_description'], 'short_description')
                ->isLonger($_short_description, NULL, 50);

        if (!\my_validator::hasErrors()) {
            $query = 'INSERT
                        INTO pictures (name, size, type, description, short_description, body)
                        VALUES (:name, :size, :type, :description, :short_description, :body);';

            $this->stmt = $this->conn->prepare($query);
            return $this->stmt->execute(array(
                        (string) $_name,
                        (int) $_size,
                        (string) $_type,
                        (string) $_description,
                        (string) $_short_description,
                        (string) file_get_contents($_tmp_name)
                    ));
        }
    }

    public function deleteById($id) {

        $query = 'DELETE
                  FROM pictures
                  WHERE id = :id;';

        $this->stmt = $this->conn->prepare($query);
        return $this->stmt->execute(array((int) $id));
    }

}

?>

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

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

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

Код: 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.
    public function fetchOne() {
        $row = $this->fetch();
        
        if (is_array($row)) {
            return current($row);
        }
        
        return false;
    }
    
    public function fetchAll() {
        $rows = array();
        
        while ($row = $this->fetch()) {
            $rows[] = $row;
        }
        
        return $rows;
    } 
    
    public function fetchCol($name) {
        $rows = $this->fetchAll();
        $column = array();
        $num = $this->numRows();
        
        if ($num > 0) {
            if (!isset($rows[0][$name])) {
                return false;
            }
        
            for ($i = 0; $i < $num; ++$i) {
                $column[] = $rows[$i][$name];
            }
        }
        
        return $column;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792354
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: 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()) {              
        static $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 .= ';';
        $this->query($sql);
        return $this;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792374
Edd.Dragon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Какой-то кодо-блог...

Нельзя завести себе акк на профильном ресурсе и туда лить свои поделки?
Ту же форум! ОБСУЖДЕНИЕ, а свалка кода
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792384
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Edd.Dragon,

Не придумал как можно сделать красиво, поэтому пришлось удалить, может кому понадобится

Код: 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 single($table, $column, $where = null) {
        $this->select($table, array('columns' => $column, 'where' => $where));
        return $this->fetchOne();
    }
    
    public function col($table, $name, $where = null) {
        $this->select($table, array('columns' => $name, 'where' => $where));
        return $this->fetchCol($name);
    }
    
    public function assoc($table, $column, $where = null) {
        $this->select($table, array('columns' => 'id, ' . $column, 'where' => $where));
        $keys = $this->fetchCol('id');
        
        if ($keys === false) {
            return false;
        }
        
        $this->seek(0); // вернулись к первому ряду
        $values = $this->fetchCol($column);
        
        if ($values === false) {
            return false;
        }
        
        return array_combine($keys, $values);
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792388
авторэта портянка не имеет никакого отношения ни к MVC, ни как демонстрационный пример обертки для базы.
это то понятно...
кроме твоего учёного! мнения, больше, вообще, ничего не существует!!!

ПыСы (задумчиво): кто же тебя зомбировал на "обертки для базы" (C)?
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37792557
Фотография r u
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
бот - генератор gavnoкода?
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793029
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
r u,

Код: 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.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
<?php

abstract class DB {
    private $conf = array('database' => null, 'prefix' => null), $link, $temp;
    
    abstract public function open($database);
    
    abstract public function close();
    
    abstract public function query($sql);
    
    abstract public function escape();
    
    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($data) {
        foreach ($data 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 $data;
    }
    
    public function valuesStr($array) {
        $array = $this->filterArray($array);
        return implode(', ', $array);
    }
    
    public function setStr($array) {
        $array = $this->filterArray($array);      
        $str = '';
        
        foreach ($array 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->valuesStr($value);

                case 'a':
                    return $this->setStr($value);
                    
                default:
                    throw new Exception("Unknown placeholder ?{$matches[3]}");
            }
        }
    }
    
    /**
     * $stmt = $db->prepare('SELECT * FROM :users WHERE login = ? AND password = ?;', $login, $password);
     * $result = $stmt->execute();
     * $user = $result->fetch();
     */
    public function prepare() {
        $this->temp = func_get_args();
        $pattern = '/:([a-z]+)|(\d*)?\?([a-z]?)/is';
        $callback = array($this, 'replaceHolders');
        $sql = preg_replace_callback($pattern, $callback, $this->temp[0]);
        $stmt = new DB_Statement($this, $sql);
        return $stmt;
    }
    
    public function select($table, $options = array()) {              
        static $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;
    }
    
    public function find($table, $id, $columns = '*') {
        $table = $this->table($table);
        $id = intval($id);
        $result = $db->query("SELECT $columns FROM $table WHERE id = $id;");
    }
    
    public function insert($table, $row, $return_insert_id = true) {
        $sql = 'INSERT INTO ' . $this->table($table);
        $sql .= ' (' . implode(', ', array_keys($row)) . ')';
        $sql .= ' VALUES(' . $this->getValuesString(array_values($row)) . ');';
        $this->query($sql);
        
        if ($return_insert_id) {
            return $this->insertId();
        }
    }

    public function update($table, $set, $id) {
        $sql = 'UPDATE ' . $this->table($table);
        $sql .= ' SET ' . $this->getArrayString($set);
        $sql .= ' WHERE id = ' . intval($id);
        $this->query($sql);
    }

    public function delete($table, $id) {
        $sql = 'DELETE FROM ' . $this->table($table);
        $sql .= ' WHERE id = ' . intval($id);
        $this->query($sql);
    }
    
    public function countRows($table, $extra = 1) {
        $result = $db->query("SELECT COUNT(*) FROM $table WHERE $extra;");
        $num = (int) $result->fetchSingle();
        return $num;
    }
    
    public function countPages($table, $limit, $extra = 1) {
        if ($limit > 0) {
            $total = $this->countRows($table, $extra);
            
            if ($total === false) {
                return false;
            }
            
            return ceil($total / $limit);
        }
    }
}

?>
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793042
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
protected $conf = array('database' => null, 'prefix' => null), $link, $temp;
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793046
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
    public function insert($table, $row, $return_insert_id = true) {
        $sql = 'INSERT INTO ' . $this->table($table);
        $sql .= ' (' . implode(', ', array_keys($row)) . ')';
        [FIXED]$sql .= ' VALUES(' . $this->valuesStr(array_values($row)) . ');';[/FIXED]
        $this->query($sql);
        
        if ($return_insert_id) {
            return $this->insertId();
        }
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793065
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: 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 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, $values, $return_insert_id = true) {
        $table = $this->table($table);
        $columns = array_keys($row);
        $values = $this->valuesStr($row);
        $this->query("INSERT INTO $table ($columns) VALUES ($values);");
        
        if ($return_insert_id) {
            return $this->insertId();
        }
    }

    public function update($table, $set, $id) {
        $table = $this->table($table);
        $set = $this->setStr($set);
        $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 countRows($table, $extra = 1) {
        $table = $this->table($table);
        $result = $db->query("SELECT COUNT(*) FROM $table WHERE $extra;");
        $num = (int) $result->fetchSingle();
        return $num;
    }
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793268
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: php
1.
2.
3.
4.
$login = 'tester';
$password = 'test';
$stmt = $db->prepare('SELECT * FROM :users WHERE login = 2? AND password = 1?s;', $password, $login);
echo $stmt;



Код: sql
1.
SELECT * FROM t_users WHERE login = 'tester' AND password = 'test';
...
Рейтинг: 0 / 0
[php] Фильтрация переменных в классе-обертке для БД
    #37793296
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: 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.
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;
    }
    
    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);
    }
}

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

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

у вас раньше аккаунта green_troll не было?

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


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