Database.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. class Application_Common_Database
  3. {
  4. const SINGLE = 'single';
  5. const COLUMN = 'column';
  6. const ALL = 'all';
  7. const EXECUTE = 'execute';
  8. const ROW_COUNT = 'row_count';
  9. public static function prepareAndExecute($sql,
  10. array $paramValueMap = array(),
  11. $type=self::ALL,
  12. $fetchType=PDO::FETCH_ASSOC,
  13. $con=null)
  14. {
  15. if (is_null($con)) {
  16. $con = Propel::getConnection();
  17. }
  18. $stmt = $con->prepare($sql);
  19. foreach ($paramValueMap as $param => $v) {
  20. $stmt->bindValue($param, $v);
  21. }
  22. $rows = array();
  23. if ($stmt->execute()) {
  24. if ($type == self::SINGLE) {
  25. $rows = $stmt->fetch($fetchType);
  26. } else if ($type == self::COLUMN){
  27. $rows = $stmt->fetchColumn();
  28. } else if ($type == self::ALL) {
  29. $rows = $stmt->fetchAll($fetchType);
  30. } else if ($type == self::EXECUTE) {
  31. $rows = null;
  32. } else if ($type == self::ROW_COUNT) {
  33. $rows = $stmt->rowCount();
  34. } else {
  35. $msg = "bad type passed: type($type)";
  36. throw new Exception("Error: $msg");
  37. }
  38. } else {
  39. $msg = implode(',', $stmt->errorInfo());
  40. throw new Exception("Error: $msg");
  41. }
  42. return $rows;
  43. }
  44. /*
  45. Wrapper around prepareAndExecute that allows you to use multipe :xx's
  46. in one query. Transforms $sql to :xx1, :xx2, ....
  47. */
  48. public static function smartPrepareAndExecute($sql, array $params,
  49. $type='all', $fetchType=PDO::FETCH_ASSOC)
  50. {
  51. $new_params = array();
  52. $new_sql = $sql;
  53. foreach ($params as $k => $v) {
  54. $matches_count = substr_count($sql, $k);
  55. if ($matches_count == 0) {
  56. throw new Exception("Argument $k is not inside $sql");
  57. } elseif ($matches_count == 1) {
  58. $new_params[$k] = $new_params[$v];
  59. } else {
  60. foreach ( range(1,$matches_count) as $i ) {
  61. preg_replace( "/$k(\D)/", "$k$i${1}", $sql, 1);
  62. $new_params[ $k.$i ] = $v;
  63. }
  64. }
  65. }
  66. return Application_Common_Database::prepareAndExecute( $new_sql,
  67. $new_params, $type, $fetchType);
  68. }
  69. }