Statement.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Statement
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Db
  24. */
  25. require_once 'Zend/Db.php';
  26. /**
  27. * @see Zend_Db_Statement_Interface
  28. */
  29. require_once 'Zend/Db/Statement/Interface.php';
  30. /**
  31. * Abstract class to emulate a PDOStatement for native database adapters.
  32. *
  33. * @category Zend
  34. * @package Zend_Db
  35. * @subpackage Statement
  36. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. abstract class Zend_Db_Statement implements Zend_Db_Statement_Interface
  40. {
  41. /**
  42. * @var Zend_Db_Adapter_Abstract
  43. */
  44. protected $_adapter = null;
  45. /**
  46. * The current fetch mode.
  47. *
  48. * @var integer
  49. */
  50. protected $_fetchMode = Zend_Db::FETCH_ASSOC;
  51. /**
  52. * Attributes.
  53. *
  54. * @var array
  55. */
  56. protected $_attribute = array();
  57. /**
  58. * Column result bindings.
  59. *
  60. * @var array
  61. */
  62. protected $_bindColumn = array();
  63. /**
  64. * Query parameter bindings; covers bindParam() and bindValue().
  65. *
  66. * @var array
  67. */
  68. protected $_bindParam = array();
  69. /**
  70. * SQL string split into an array at placeholders.
  71. *
  72. * @var array
  73. */
  74. protected $_sqlSplit = array();
  75. /**
  76. * Parameter placeholders in the SQL string by position in the split array.
  77. *
  78. * @var array
  79. */
  80. protected $_sqlParam = array();
  81. /**
  82. * @var Zend_Db_Profiler_Query
  83. */
  84. protected $_queryId = null;
  85. /**
  86. * Constructor for a statement.
  87. *
  88. * @param Zend_Db_Adapter_Abstract $adapter
  89. * @param mixed $sql Either a string or Zend_Db_Select.
  90. */
  91. public function __construct($adapter, $sql)
  92. {
  93. $this->_adapter = $adapter;
  94. if ($sql instanceof Zend_Db_Select) {
  95. $sql = $sql->assemble();
  96. }
  97. $this->_parseParameters($sql);
  98. $this->_prepare($sql);
  99. $this->_queryId = $this->_adapter->getProfiler()->queryStart($sql);
  100. }
  101. /**
  102. * @param string $sql
  103. * @return void
  104. */
  105. protected function _parseParameters($sql)
  106. {
  107. $sql = $this->_stripQuoted($sql);
  108. // split into text and params
  109. $this->_sqlSplit = preg_split('/(\?|\:[a-zA-Z0-9_]+)/',
  110. $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  111. // map params
  112. $this->_sqlParam = array();
  113. foreach ($this->_sqlSplit as $key => $val) {
  114. if ($val == '?') {
  115. if ($this->_adapter->supportsParameters('positional') === false) {
  116. /**
  117. * @see Zend_Db_Statement_Exception
  118. */
  119. require_once 'Zend/Db/Statement/Exception.php';
  120. throw new Zend_Db_Statement_Exception("Invalid bind-variable position '$val'");
  121. }
  122. } else if ($val[0] == ':') {
  123. if ($this->_adapter->supportsParameters('named') === false) {
  124. /**
  125. * @see Zend_Db_Statement_Exception
  126. */
  127. require_once 'Zend/Db/Statement/Exception.php';
  128. throw new Zend_Db_Statement_Exception("Invalid bind-variable name '$val'");
  129. }
  130. }
  131. $this->_sqlParam[] = $val;
  132. }
  133. // set up for binding
  134. $this->_bindParam = array();
  135. }
  136. /**
  137. * Remove parts of a SQL string that contain quoted strings
  138. * of values or identifiers.
  139. *
  140. * @param string $sql
  141. * @return string
  142. */
  143. protected function _stripQuoted($sql)
  144. {
  145. // get the character for delimited id quotes,
  146. // this is usually " but in MySQL is `
  147. $d = $this->_adapter->quoteIdentifier('a');
  148. $d = $d[0];
  149. // get the value used as an escaped delimited id quote,
  150. // e.g. \" or "" or \`
  151. $de = $this->_adapter->quoteIdentifier($d);
  152. $de = substr($de, 1, 2);
  153. $de = str_replace('\\', '\\\\', $de);
  154. // get the character for value quoting
  155. // this should be '
  156. $q = $this->_adapter->quote('a');
  157. $q = $q[0];
  158. // get the value used as an escaped quote,
  159. // e.g. \' or ''
  160. $qe = $this->_adapter->quote($q);
  161. $qe = substr($qe, 1, 2);
  162. $qe = str_replace('\\', '\\\\', $qe);
  163. // get a version of the SQL statement with all quoted
  164. // values and delimited identifiers stripped out
  165. // remove "foo\"bar"
  166. $sql = preg_replace("/$q($qe|\\\\{2}|[^$q])*$q/", '', $sql);
  167. // remove 'foo\'bar'
  168. if (!empty($q)) {
  169. $sql = preg_replace("/$q($qe|[^$q])*$q/", '', $sql);
  170. }
  171. return $sql;
  172. }
  173. /**
  174. * Bind a column of the statement result set to a PHP variable.
  175. *
  176. * @param string $column Name the column in the result set, either by
  177. * position or by name.
  178. * @param mixed $param Reference to the PHP variable containing the value.
  179. * @param mixed $type OPTIONAL
  180. * @return bool
  181. */
  182. public function bindColumn($column, &$param, $type = null)
  183. {
  184. $this->_bindColumn[$column] =& $param;
  185. return true;
  186. }
  187. /**
  188. * Binds a parameter to the specified variable name.
  189. *
  190. * @param mixed $parameter Name the parameter, either integer or string.
  191. * @param mixed $variable Reference to PHP variable containing the value.
  192. * @param mixed $type OPTIONAL Datatype of SQL parameter.
  193. * @param mixed $length OPTIONAL Length of SQL parameter.
  194. * @param mixed $options OPTIONAL Other options.
  195. * @return bool
  196. */
  197. public function bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
  198. {
  199. if (!is_int($parameter) && !is_string($parameter)) {
  200. /**
  201. * @see Zend_Db_Statement_Exception
  202. */
  203. require_once 'Zend/Db/Statement/Exception.php';
  204. throw new Zend_Db_Statement_Exception('Invalid bind-variable position');
  205. }
  206. $position = null;
  207. if (($intval = (int) $parameter) > 0 && $this->_adapter->supportsParameters('positional')) {
  208. if ($intval >= 1 || $intval <= count($this->_sqlParam)) {
  209. $position = $intval;
  210. }
  211. } else if ($this->_adapter->supportsParameters('named')) {
  212. if ($parameter[0] != ':') {
  213. $parameter = ':' . $parameter;
  214. }
  215. if (in_array($parameter, $this->_sqlParam) !== false) {
  216. $position = $parameter;
  217. }
  218. }
  219. if ($position === null) {
  220. /**
  221. * @see Zend_Db_Statement_Exception
  222. */
  223. require_once 'Zend/Db/Statement/Exception.php';
  224. throw new Zend_Db_Statement_Exception("Invalid bind-variable position '$parameter'");
  225. }
  226. // Finally we are assured that $position is valid
  227. $this->_bindParam[$position] =& $variable;
  228. return $this->_bindParam($position, $variable, $type, $length, $options);
  229. }
  230. /**
  231. * Binds a value to a parameter.
  232. *
  233. * @param mixed $parameter Name the parameter, either integer or string.
  234. * @param mixed $value Scalar value to bind to the parameter.
  235. * @param mixed $type OPTIONAL Datatype of the parameter.
  236. * @return bool
  237. */
  238. public function bindValue($parameter, $value, $type = null)
  239. {
  240. return $this->bindParam($parameter, $value, $type);
  241. }
  242. /**
  243. * Executes a prepared statement.
  244. *
  245. * @param array $params OPTIONAL Values to bind to parameter placeholders.
  246. * @return bool
  247. */
  248. public function execute(array $params = null)
  249. {
  250. /*
  251. * Simple case - no query profiler to manage.
  252. */
  253. if ($this->_queryId === null) {
  254. return $this->_execute($params);
  255. }
  256. /*
  257. * Do the same thing, but with query profiler
  258. * management before and after the execute.
  259. */
  260. $prof = $this->_adapter->getProfiler();
  261. $qp = $prof->getQueryProfile($this->_queryId);
  262. if ($qp->hasEnded()) {
  263. $this->_queryId = $prof->queryClone($qp);
  264. $qp = $prof->getQueryProfile($this->_queryId);
  265. }
  266. if ($params !== null) {
  267. $qp->bindParams($params);
  268. } else {
  269. $qp->bindParams($this->_bindParam);
  270. }
  271. $qp->start($this->_queryId);
  272. $retval = $this->_execute($params);
  273. $prof->queryEnd($this->_queryId);
  274. return $retval;
  275. }
  276. /**
  277. * Returns an array containing all of the result set rows.
  278. *
  279. * @param int $style OPTIONAL Fetch mode.
  280. * @param int $col OPTIONAL Column number, if fetch mode is by column.
  281. * @return array Collection of rows, each in a format by the fetch mode.
  282. */
  283. public function fetchAll($style = null, $col = null)
  284. {
  285. $data = array();
  286. if ($style === Zend_Db::FETCH_COLUMN && $col === null) {
  287. $col = 0;
  288. }
  289. if ($col === null) {
  290. while ($row = $this->fetch($style)) {
  291. $data[] = $row;
  292. }
  293. } else {
  294. while (false !== ($val = $this->fetchColumn($col))) {
  295. $data[] = $val;
  296. }
  297. }
  298. return $data;
  299. }
  300. /**
  301. * Returns a single column from the next row of a result set.
  302. *
  303. * @param int $col OPTIONAL Position of the column to fetch.
  304. * @return string One value from the next row of result set, or false.
  305. */
  306. public function fetchColumn($col = 0)
  307. {
  308. $data = array();
  309. $col = (int) $col;
  310. $row = $this->fetch(Zend_Db::FETCH_NUM);
  311. if (!is_array($row)) {
  312. return false;
  313. }
  314. return $row[$col];
  315. }
  316. /**
  317. * Fetches the next row and returns it as an object.
  318. *
  319. * @param string $class OPTIONAL Name of the class to create.
  320. * @param array $config OPTIONAL Constructor arguments for the class.
  321. * @return mixed One object instance of the specified class, or false.
  322. */
  323. public function fetchObject($class = 'stdClass', array $config = array())
  324. {
  325. $obj = new $class($config);
  326. $row = $this->fetch(Zend_Db::FETCH_ASSOC);
  327. if (!is_array($row)) {
  328. return false;
  329. }
  330. foreach ($row as $key => $val) {
  331. $obj->$key = $val;
  332. }
  333. return $obj;
  334. }
  335. /**
  336. * Retrieve a statement attribute.
  337. *
  338. * @param string $key Attribute name.
  339. * @return mixed Attribute value.
  340. */
  341. public function getAttribute($key)
  342. {
  343. if (array_key_exists($key, $this->_attribute)) {
  344. return $this->_attribute[$key];
  345. }
  346. }
  347. /**
  348. * Set a statement attribute.
  349. *
  350. * @param string $key Attribute name.
  351. * @param mixed $val Attribute value.
  352. * @return bool
  353. */
  354. public function setAttribute($key, $val)
  355. {
  356. $this->_attribute[$key] = $val;
  357. }
  358. /**
  359. * Set the default fetch mode for this statement.
  360. *
  361. * @param int $mode The fetch mode.
  362. * @return bool
  363. * @throws Zend_Db_Statement_Exception
  364. */
  365. public function setFetchMode($mode)
  366. {
  367. switch ($mode) {
  368. case Zend_Db::FETCH_NUM:
  369. case Zend_Db::FETCH_ASSOC:
  370. case Zend_Db::FETCH_BOTH:
  371. case Zend_Db::FETCH_OBJ:
  372. $this->_fetchMode = $mode;
  373. break;
  374. case Zend_Db::FETCH_BOUND:
  375. default:
  376. $this->closeCursor();
  377. /**
  378. * @see Zend_Db_Statement_Exception
  379. */
  380. require_once 'Zend/Db/Statement/Exception.php';
  381. throw new Zend_Db_Statement_Exception('invalid fetch mode');
  382. break;
  383. }
  384. }
  385. /**
  386. * Helper function to map retrieved row
  387. * to bound column variables
  388. *
  389. * @param array $row
  390. * @return bool True
  391. */
  392. public function _fetchBound($row)
  393. {
  394. foreach ($row as $key => $value) {
  395. // bindColumn() takes 1-based integer positions
  396. // but fetch() returns 0-based integer indexes
  397. if (is_int($key)) {
  398. $key++;
  399. }
  400. // set results only to variables that were bound previously
  401. if (isset($this->_bindColumn[$key])) {
  402. $this->_bindColumn[$key] = $value;
  403. }
  404. }
  405. return true;
  406. }
  407. /**
  408. * Gets the Zend_Db_Adapter_Abstract for this
  409. * particular Zend_Db_Statement object.
  410. *
  411. * @return Zend_Db_Adapter_Abstract
  412. */
  413. public function getAdapter()
  414. {
  415. return $this->_adapter;
  416. }
  417. }