Шаг 5
Сложные запросы
Всё вроде как у нас вышло удачно. Однако это до поры до времени. А именно до тех пор, пока мы делаем простую выборку. А вот если нам потребуется сложный запрос (отлистать результаты поиска к примеру), то наш класс тут же пикнет. Нужно это упущение немедленно устранить.
Сделать это оказывается не так уж и сложно. Дело в том, что в SQL есть одна замечательная опция - SQL_CALC_FOUND_ROWS. Если включить её, то в одном запросе фактически будет выполнено два. Один - основной, с количеством строк, установленном в лимите, другой подсчитает количество строк всего, не взирая на установленный лимит. И мы сможем узнать это количество следующим запросом. Чтобы было проще понять, можно запустить такой скрипт:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
<?php
include './mysql.php';
// Запрос $res = mysql_query("SELECT * FROM `table` WHERE `text` LIKE '%2%'");
// Формируем вывод $table = "<table width=\"50%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\">\n";
if(mysql_num_rows($res) > 0) while($row = mysql_fetch_assoc($res)) { $table .= "<tr>\n<td>\n\t". $row['text']. "\n</td>\n</tr>\n"; } $table .= "</table>\n"; echo $table;
|
Он явит нам на свет все записи, содержащие двойку. Теперь поставим ему лимит и включим опцию SQL_CALC_FOUND_ROWS, а следующим запросом посмотрим, сколько он насчитает нам записей:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 |
<?php
include './mysql.php';
// Запрос $res = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM `table` WHERE `text` LIKE '%2%' LIMIT 0, 10"); // Считаем, сколько записей удовлетворяют условиям $cnt = mysql_result(mysql_query('SELECT FOUND_ROWS()'), 0);
// Формируем вывод $table = "<table width=\"50%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\">\n";
if(mysql_num_rows($res) > 0) while($row = mysql_fetch_assoc($res)) { $table .= "<tr>\n<td>\n\t". $row['text']. "\n</td>\n</tr>\n"; } $table .= "</table>\n"; echo $table; echo 'Всего найдено '. $cnt .' строк'
|
Вот на этом принципе мы и построим новый метод, который будем запускать в случае, если потребуется отлистать сложный запрос:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 |
<?php
/** * Operates a cache of difficult inquiries * @param string $query * @access public * @return void */ public function calcQuery($query) { // Заменяем SELECT на SELECT SQL_CALC_FOUND_ROWS $query = preg_replace('#SELECT#i', 'SELECT SQL_CALC_FOUND_ROWS ', $query); // Выполняем основной запрос $res = mysql_query($query . ' LIMIT '. $this->NumPage .', '. $this->NumRows * $this->NumColumns); // Считаем к-во рядов $this->TableCount = mysql_result(mysql_query('SELECT FOUND_ROWS()'), 0); // Запускаем метод для менюшки $this->createLimit(); return $res; }
|
У Вас может возникнуть вопрос - а почему отдельным методом. Почему это не сделать сразу?
Ответ тревиален. Дело в том, что запрос с SQL_CALC_FOUND_ROWS работает гораздо медленнее, чем обычный. И использовать его нужно только там, где это действительно необходимо.
Когда потребуется отлистать результаты сложного запроса, вместо метода countQuery() нужно вызвать метод calcQuery() и все будет чики-пики.
Ну а вот и полный текст класса:
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
|
<?php
include './mysql.php';
/** * IRB_Paginator - Class of division of the information on a paginal mode * NOTE: Requires PHP version 5 or later * @package IRB_Paginator * @author IT studio IRBIS-team (www.irbis-team.com) * @copyright © 2010 IRBIS-team * @version 0.1 * @license http://www.opensource.org/licenses/rpl1.5.txt */
class IRB_Paginator { ///////////////////////////////////////////////// // PUBLIC ///////////////////////////////////////////////// /** * Establishes page number. * @var int */ public $NumPage = 1; /** * Establishes quantity of numbers. * @var int */ public $NumRows = 1; /** * Establishes quantity of columns. * @var int */ public $NumColumns = 1; /** * Includes mod_rewrite. * @var string */ public $LevelPage = 'page'; ///////////////////////////////////////////////// // PROPERTIES AND PRIVATE ////////////////////////////////////////////////
private $TableTotal = 0; private $TableCount = 0; private $StartLink = ''; /** * Constructor * @param int $page * @param int $rows * @param int $columns */ public function __construct($page = 1, $rows = 1, $columns = 1) { if($rows > 1) $this->NumPage = (int)$page; if($rows > 1) $this->NumRows = $rows;
if($columns > 1) $this->NumColumns = $columns; }
/** * Operates a cache of difficult inquiries * @param string $query * @access public * @return void */ public function countQuery($query) { $query = str_replace("\n", " ", $query); preg_match("#FROM(.+)#i", $query, $table); $result = mysql_query("SELECT COUNT(*) AS `cnt` FROM ". $table[1]); $this->TableCount = mysql_result($result, 0); $res = mysql_query($query . $this->createLimit()); return $res; } /** * Operates a cache of difficult inquiries * @param string $query * @access public * @return void */ public function calcQuery($query) { // Заменяем SELECT на SELECT SQL_CALC_FOUND_ROWS $query = preg_replace('#SELECT#i', 'SELECT SQL_CALC_FOUND_ROWS ', $query); // Выполняем основной запрос $res = mysql_query($query . ' LIMIT '. $this->NumPage .', '. $this->NumRows * $this->NumColumns); // Считаем к-во рядов $this->TableCount = mysql_result(mysql_query('SELECT FOUND_ROWS()'), 0); // Запускаем метод для менюшки $this->createLimit(); return $res; } /** * Calculates a position and prepares a limit for inquiry * @param int $page * @access public * @return string */ public function createLimit() { $this->TableTotal = intval(($this->TableCount - $this->NumColumns) / $this->NumRows * $this->NumColumns) - 1; if($this->NumPage < 1) $this->NumPage = 1; if(empty($this->TableTotal) || $this->TableTotal < $this->TableCount) $this->TableTotal = $this->TableCount; if($this->NumPage > $this->TableTotal) $this->NumPage = $this->TableTotal; $start = $this->NumPage * $this->NumRows * $this->NumColumns - $this->NumRows * $this->NumColumns; if($start < 0) $start = 0; return ' LIMIT '. $start .', '. $this->NumRows * $this->NumColumns; }
/** * Generates the navigation menu * @access private * @param string $link * @return string */ function createMenu($rewrite = false, $level = '') { if(!empty($level)) $this->LevelPage = $level; $this->SetRewrite = $rewrite; $this->StartLink = $rewrite ? $this->LevelPage .'/' : '?'. $this->LevelPage .'='; $count = ceil($this->TableTotal / $this->NumRows / $this->NumColumns); $menu = "\n<!-- IRB_Paginator begin -->\n";
if($count < 13) { $i = 1; $cnt = $count; } else { if($this->NumPage > 10) $menu .= $this->createLink(($this->NumPage - 10), '-10<', '_top'); if($count > 12) { if($this->NumPage == 7) $menu .= $this->createLink(1, 1); elseif($this->NumPage == 8) $menu .= $this->createLink(1, 1) . $this->createLink(2, 2); elseif($this->NumPage > 7) $menu .= $this->createLink(1, 1) . $this->createLink(2, 2) . $this->createLink(0, '...', '_top', false); }
if($this->NumPage < 6)
{ $i = 1; $cnt = 10; } elseif($this->NumPage >= $count - 5) { $i = $count - 10; $cnt = $count; } else { $i = $this->NumPage - 5; $cnt = $count; }
if($this->NumPage < 6) $cnt = $i + 9; elseif($count - $i > 10) $cnt = $i + 10;
}
while($i <= $cnt) { if($i == $this->NumPage) $menu .= $this->createLink($i, $i, '_active', false); else $menu .= $this->createLink($i, $i); $i++; } if($count > 12) { if($this->NumPage < $count - 6) $menu .= $this->createLink(0, '...', '_top', false) . $this->createLink(($count - 1), ($count - 1)); if($this->NumPage < $count - 5) $menu .= $this->createLink($count, $count); } $end = ($this->NumPage + 10 > $count) ? $count : $this->NumPage + 10; if($this->NumPage < $count - 5 && $count - $this->NumPage >= 10) $menu .= $this->createLink($end, '>+10', '_top'); return $menu ."\n\n<!-- IRB_Paginator end -->\n"; }
/** * Makes a hyperlink * @param int $page * @param string $link, $class * @param bolean $active * @access private * @return string */ private function createLink($page = 1, $link = '', $class = '', $active = true) { if(strpos($_SERVER['REQUEST_URI'], $this->LevelPage) === false) $string = $this->StartLink . $page; else { if($this->SetRewrite) $string = preg_replace('#'. $this->LevelPage .'/\d+#', $this->LevelPage .'/'. $page, $_SERVER['REQUEST_URI']); else $string = '?'. preg_replace('#'. $this->LevelPage .'=\d+#', $this->LevelPage .'='. $page, $_SERVER['QUERY_STRING']); }
if(empty($link)) $link = $page; if($active) return "<span class=\"IRB_paginator". $class ."\">\n" . "<a href=\"". $string ."\" />". $link ."</a>\n</span>\n"; else return "<span class=\"IRB_paginator". $class ."\"> ". $link ." </span>\n"; } }
|
Образец есть в меню.
А если Вы пользуетесь нашим движком, то вот тут адаптированный вариант класса.
|