Pdo.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. class Core_Pdo extends PDO {
  3. protected $_database_name;
  4. protected $_zasob_id;
  5. // public PDO::__construct ( string $dsn [, string $username [, string $password [, array $options ]]] )
  6. public function __construct($dsn, $username, $password, $options = array()) {
  7. $this->_database_name = $options['database'];
  8. $this->_zasob_id = $options['zasob_id'];
  9. unset($options['database']);
  10. unset($options['zasob_id']);
  11. parent::__construct($dsn, $username, $password, $options);
  12. $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  13. $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  14. }
  15. public function getDatabaseName() {
  16. return $this->_database_name;
  17. }
  18. public function getZasobId() {
  19. return $this->_zasob_id;
  20. }
  21. public function fetchAll($sql) {
  22. $sth = $this->prepare($sql);
  23. $sth->execute();
  24. return $sth->fetchAll();
  25. }
  26. public function bindValues($sth, $values) {
  27. foreach ($values as $name => $value) {
  28. $val = $value;
  29. $type = PDO::PARAM_STR;
  30. if (is_array($value)) {
  31. $val = $value[0];
  32. if (count($value) > 1) {
  33. $type = $value[1];
  34. }
  35. }
  36. $sth->bindValue($name, $val, $type);
  37. if (!isset($sth->bindedValues)) $sth->bindedValues = array();
  38. $sth->bindedValues[$name] = array($val, $type);
  39. }
  40. }
  41. public function getRawSql($sth, $values = array()) {
  42. $sql = $sth->queryString;
  43. $params = array();
  44. if (!empty($sth->bindedValues)) {
  45. foreach ($sth->bindedValues as $name => $value) {
  46. $params[$name] = array($value[0], $value[1]);
  47. }
  48. }
  49. foreach ($values as $name => $value) {
  50. $val = $value;
  51. $type = PDO::PARAM_STR;
  52. if (is_array($value)) {
  53. $val = $value[0];
  54. if (count($value) > 1) {
  55. $type = $value[1];
  56. }
  57. }
  58. $params[$name] = array($val, $type);
  59. }
  60. if (!empty($params)) {
  61. foreach ($params as $name => $val) {
  62. $outValue = $val[0];
  63. if (PDO::PARAM_STR == $val[1]) $outValue = "'{$outValue}'";
  64. $sql = str_replace(":{$name}", $outValue, $sql);
  65. }
  66. }
  67. return $sql;
  68. }
  69. }