Advertisement
Guest User

Untitled

a guest
May 11th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. class Connection
  2. {
  3. private $username = "xxxx";
  4. private $password = "xxxx";
  5. private $dsn = "mysql:host=host;dbname=name_db";
  6. private $sql;
  7. private $DBH;
  8.  
  9. function setSQL($sql){
  10. $this->sql = $sql; //if $sql is not set it troughs an error at PDOException
  11. }
  12.  
  13. public function query()
  14. {
  15. //the connection will get established here if it hasn't been already
  16. if (is_null($this->DBH))
  17. try {
  18. $this->DBH = new PDO( $this->dsn, $this->username, $this->password );
  19. $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  20.  
  21. //query
  22. $result = $this->DBH->prepare($this->sql);
  23. $result->execute();
  24. return $result->fetch(PDO::FETCH_ASSOC);
  25.  
  26. } catch(PDOException $e) {
  27.  
  28. echo "I'm afraid I can't do that1.";
  29. //file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
  30. }
  31. }
  32.  
  33. //clear connection and variables
  34. function __destruct(){
  35. $this->DBH = null;
  36. }
  37.  
  38. }
  39.  
  40. $sql = "SELECT * from stock WHERE id = 302";
  41. $test = new Connection();
  42. $test->setSQL($sql);
  43. echo $test->query();
  44.  
  45. class ApplicationResourcePool
  46. {
  47. static var $_dbHandle;
  48.  
  49. private static $_dbConfig = array(
  50. 'dsn' => '',
  51. 'username' => '',
  52. 'password' => '',
  53.  
  54. );
  55. public static getDbHandle(){
  56. if(self::$_dbHandle == null){
  57. self::$_dbHandle = new PDO(
  58. self::$_dbConfig['dsn'] ,
  59. self::$_dbConfig['username'],
  60. self::$_dbConfig['password']
  61. );
  62. }
  63. return self::$_dbHandle;
  64. }
  65.  
  66. }
  67.  
  68. class StockMapper
  69. {
  70. protected $_dbh;
  71. public __construct($dbh = null)
  72. {
  73. if($dbh == null){
  74. $this->_dbh = ApplicationResourcePool::getDbHandle();
  75. } else {
  76. $this->_dbh = $dbh;
  77. }
  78.  
  79. }
  80. public getStockById($stockId){
  81.  
  82. $sth=$this->_dbh->prepare("SELECT * from stock WHERE id = :stockId");
  83. $sth->bindParam(":stockId", $stockId);
  84. $sth->execute();
  85. $result = $sth->fetch(PDO::FETCH_ASSOC);
  86. return $result[0];
  87. }
  88. }
  89.  
  90. $stockMapper = new StockMapper();
  91. $stockData = $stockMapper->getStockById('302');
  92.  
  93. SELECT * from stock WHERE id = ?
  94.  
  95. array(302)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement