Statement.php 13 KB

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