2 /***************************************************************
5 * (c) 2010 Xavier Perseguers <typo3@perseguers.ch>
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
29 * TYPO3 prepared statement for t3lib_db class.
32 * In all TYPO3 scripts when you need to create a prepared query:
34 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'pages', 'uid = :uid');
35 * $statement->execute(array(':uid' => 2));
36 * while (($row = $statement->fetch()) !== FALSE) {
42 * @author Xavier Perseguers <typo3@perseguers.ch>
46 class t3lib_db_PreparedStatement
{
49 * Represents the SQL NULL data type.
55 * Represents the SQL INTEGER data type.
61 * Represents the SQL CHAR, VARCHAR, or other string data type.
67 * Represents a boolean data type.
73 * Automatically detects underlying type
76 const PARAM_AUTOTYPE
= 4;
79 * Specifies that the fetch method shall return each row as an array indexed by
80 * column name as returned in the corresponding result set. If the result set
81 * contains multiple columns with the same name, t3lib_db_PreparedStatement::FETCH_ASSOC
82 * returns only a single value per column name.
85 const FETCH_ASSOC
= 2;
88 * Specifies that the fetch method shall return each row as an array indexed by
89 * column number as returned in the corresponding result set, starting at column 0.
95 * Query to be executed.
101 * Components of the query to be executed.
104 protected $precompiledQueryParts;
107 * Table (used to call $GLOBALS['TYPO3_DB']->fullQuoteStr().
113 * Binding parameters.
116 protected $parameters;
119 * Default fetch mode.
122 protected $defaultFetchMode = self
::FETCH_ASSOC
;
125 * MySQL result pointer (of SELECT query) / DBAL object.
131 * Creates a new PreparedStatement. Either $query or $queryComponents
132 * should be used. Typically $query will be used by native MySQL TYPO3_DB
133 * on a ready-to-be-executed query. On the other hand, DBAL will have
134 * parse the query and will be able to safely know where parameters are used
135 * and will use $queryComponents instead.
136 * This constructor may only be used by t3lib_DB.
138 * @param string $query SQL query to be executed
139 * @param string FROM table, used to call $GLOBALS['TYPO3_DB']->fullQuoteStr().
140 * @param array $precompiledQueryParts Components of the query to be executed
143 public function __construct($query, $table, array $precompiledQueryParts = array()) {
144 $this->query
= $query;
145 $this->precompiledQueryParts
= $precompiledQueryParts;
146 $this->table
= $table;
147 $this->parameters
= array();
148 $this->resource
= NULL
;
152 * Binds an array of values to corresponding named or question mark placeholders in the SQL
153 * statement that was use to prepare the statement.
157 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = ? AND bug_status = ?');
158 * $statement->bindValues(array('goofy', 'FIXED'));
163 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = :nickname AND bug_status = :status');
164 * $statement->bindValues(array(':nickname' => 'goofy', ':status' => 'FIXED'));
167 * @param array $values The values to bind to the parameter. The PHP type of each array value will be used to decide which PARAM_* type to use (int, string, boolean, null), so make sure your variables are properly casted, if needed.
168 * @return t3lib_db_PreparedStatement The current prepared statement to allow method chaining
171 public function bindValues(array $values) {
172 foreach ($values as $parameter => $value) {
173 $key = is_int($parameter) ?
$parameter +
1 : $parameter;
174 $this->bindValue($key, $value, self
::PARAM_AUTOTYPE
);
181 * Binds a value to a corresponding named or question mark placeholder in the SQL
182 * statement that was use to prepare the statement.
186 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = ? AND bug_status = ?');
187 * $statement->bindValue(1, 'goofy');
188 * $statement->bindValue(2, 'FIXED');
193 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = :nickname AND bug_status = :status');
194 * $statement->bindValue(':nickname', 'goofy');
195 * $statement->bindValue(':status', 'FIXED');
198 * @param mixed $parameter Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
199 * @param mixed $value The value to bind to the parameter.
200 * @param integer $data_type Explicit data type for the parameter using the t3lib_db_PreparedStatement::PARAM_* constants. If not given, the PHP type of the value will be used instead (int, string, boolean).
201 * @return t3lib_db_PreparedStatement The current prepared statement to allow method chaining
204 public function bindValue($parameter, $value, $data_type = self
::PARAM_AUTOTYPE
) {
205 switch ($data_type) {
206 case self
::PARAM_INT
:
207 if (!is_int($value)) {
208 throw new InvalidArgumentException('$value is not an integer as expected: ' . $value, 1281868686);
211 case self
::PARAM_BOOL
:
212 if (!is_bool($value)) {
213 throw new InvalidArgumentException('$value is not a boolean as expected: ' . $value, 1281868687);
216 case self
::PARAM_NULL
:
217 if (!is_null($value)) {
218 throw new InvalidArgumentException('$value is not NULL as expected: ' . $value, 1282489834);
223 $key = is_int($parameter) ?
$parameter - 1 : $parameter;
224 $this->parameters
[$key] = array(
226 'type' => ($data_type == self
::PARAM_AUTOTYPE ?
$this->guessValueType($value) : $data_type),
233 * Executes the prepared statement. If the prepared statement included parameter
234 * markers, you must either:
236 * <li>call {@link t3lib_db_PreparedStatement::bindParam()} to bind PHP variables
237 * to the parameter markers: bound variables pass their value as input</li>
238 * <li>or pass an array of input-only parameter values</li>
241 * $input_parameters behave as in {@link t3lib_db_PreparedStatement::bindParams()}
242 * and work for both named parameters and question mark parameters.
246 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = ? AND bug_status = ?');
247 * $statement->execute(array('goofy', 'FIXED'));
252 * $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', 'bugs', 'reported_by = :nickname AND bug_status = :status');
253 * $statement->execute(array(':nickname' => 'goofy', ':status' => 'FIXED'));
256 * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. The PHP type of each array value will be used to decide which PARAM_* type to use (int, string, boolean, null), so make sure your variables are properly casted, if needed.
257 * @return boolean Returns TRUE on success or FALSE on failure.
260 public function execute(array $input_parameters = array()) {
261 $query = $this->query
;
262 $precompiledQueryParts = $this->precompiledQueryParts
;
263 $parameterValues = $this->parameters
;
265 if (count($input_parameters) > 0) {
266 $parameterValues = array();
267 foreach ($input_parameters as $key => $value) {
268 $parameterValues[$key] = array(
270 'type' => $this->guessValueType($value),
275 $this->replaceValuesInQuery($query, $precompiledQueryParts, $parameterValues);
276 if (count($precompiledQueryParts) > 0) {
277 $query = implode('', $precompiledQueryParts['queryParts']);
279 $this->resource
= $GLOBALS['TYPO3_DB']->exec_PREPAREDquery($query, $precompiledQueryParts);
281 // Empty binding parameters
282 $this->parameters
= array();
284 // Return the success flag
285 return ($this->resource ? TRUE
: FALSE
);
289 * Fetches a row from a result set associated with a t3lib_db_PreparedStatement object.
291 * @param integer $fetch_style Controls how the next row will be returned to the caller. This value must be one of the t3lib_db_PreparedStatement::FETCH_* constants. If omitted, default fetch mode for this prepared query will be used.
292 * @return array Array of rows or FALSE if there are no more rows.
295 public function fetch($fetch_style = 0) {
296 if ($fetch_style == 0) {
297 $fetch_style = $this->defaultFetchMode
;
299 switch ($fetch_style) {
300 case self
::FETCH_ASSOC
:
301 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($this->resource
);
303 case self
::FETCH_NUM
:
304 $row = $GLOBALS['TYPO3_DB']->sql_fetch_row($this->resource
);
307 throw new InvalidArgumentException('$fetch_style must be either t3lib_db_PreparedStatement::FETCH_ASSOC or t3lib_db_PreparedStatement::FETCH_NUM', 1281646455);
313 * Moves internal result pointer.
315 * @param integer $rowNumber Where to place the result pointer (0 = start)
316 * @return boolean Returns TRUE on success or FALSE on failure.
319 public function seek($rowNumber) {
320 return $GLOBALS['TYPO3_DB']->sql_data_seek($this->resource
, intval($rowNumber));
324 * Returns an array containing all of the result set rows.
326 * @param integer $fetch_style Controls the contents of the returned array as documented in {@link t3lib_db_PreparedStatement::fetch()}.
327 * @return array Array of rows.
330 public function fetchAll($fetch_style = 0) {
332 while (($row = $this->fetch($fetch_style)) !== FALSE
) {
339 * Releases the cursor. Should always be call after having fetched rows from
345 public function free() {
346 $GLOBALS['TYPO3_DB']->sql_free_result($this->resource
);
350 * Returns the number of rows affected by the last SQL statement.
352 * @return integer The number of rows.
355 public function rowCount() {
356 return $GLOBALS['TYPO3_DB']->sql_num_rows($this->resource
);
360 * Returns the error number on the last execute() call.
362 * @return integer Driver specific error code.
365 public function errorCode() {
366 return $GLOBALS['TYPO3_DB']->sql_errno();
370 * Returns an array of error information about the last operation performed by this statement handle.
371 * The array consists of the following fields:
373 * <li>Driver specific error code.</li>
374 * <li>Driver specific error message</li>
377 * @return array Array of error information.
379 public function errorInfo() {
381 $GLOBALS['TYPO3_DB']->sql_errno(),
382 $GLOBALS['TYPO3_DB']->sql_error(),
387 * Sets the default fetch mode for this prepared query.
389 * @param integer $mode One of the t3lib_db_PreparedStatement::FETCH_* constants
393 public function setFetchMode($mode) {
395 case self
::FETCH_ASSOC
:
396 case self
::FETCH_NUM
:
397 $this->defaultFetchMode
= $mode;
400 throw new InvalidArgumentException('$mode must be either t3lib_db_PreparedStatement::FETCH_ASSOC or t3lib_db_PreparedStatement::FETCH_NUM', 1281875340);
405 * Guesses the type of a given value.
407 * @param mixed $value
408 * @return integer One of the t3lib_db_PreparedStatement::PARAM_* constants
410 protected function guessValueType($value) {
411 if (is_bool($value)) {
412 $type = self
::PARAM_BOOL
;
413 } elseif (is_int($value)) {
414 $type = self
::PARAM_INT
;
415 } elseif (is_null($value)) {
416 $type = self
::PARAM_NULL
;
418 $type = self
::PARAM_STR
;
425 * Replaces values for each parameter in a query.
427 * @param string $query
428 * @param array $precompiledQueryParts
429 * @param array $parameterValues
432 protected function replaceValuesInQuery(&$query, array &$precompiledQueryParts, array $parameterValues) {
433 foreach ($parameterValues as $key => $typeValue) {
434 switch ($typeValue['type']) {
435 case self
::PARAM_NULL
:
438 case self
::PARAM_INT
:
439 $value = intval($typeValue['value']);
441 case self
::PARAM_STR
:
442 $value = $GLOBALS['TYPO3_DB']->fullQuoteStr($typeValue['value'], $this->table
);
444 case self
::PARAM_BOOL
:
445 $value = $typeValue['value'] ?
1 : 0;
448 throw new InvalidArgumentException(
449 sprintf('Unknown type %s used for parameter %s.', $typeValue['type'], $key),
455 if (count($precompiledQueryParts['queryParts']) > 0) {
456 $precompiledQueryParts['queryParts'][2 * $key +
1] = $value;
458 $parts = explode('?', $query, 2);
460 $query = implode('', $parts);
463 if (!preg_match('/^:[\w]+$/', $key)) {
464 throw new InvalidArgumentException('Parameter names must start with ":" followed by an arbitrary number of alphanumerical characters.', 1282348825);
467 for ($i = 1; $i < count($precompiledQueryParts['queryParts']); $i++
) {
468 if ($precompiledQueryParts['queryParts'][$i] === $key) {
469 $precompiledQueryParts['queryParts'][$i] = $value;
472 // Replace the marker (not preceeded by a word character or a ':' but
473 // followed by a word boundary)
474 $query = preg_replace('/(?<![\w:])' . $key . '\b/', $value, $query);
481 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/db/class.t3lib_db_PreparedStatement.php']) {
482 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/db/class.t3lib_db_PreparedStatement.php']);