Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Connection
- {
- private $username = "xxxx";
- private $password = "xxxx";
- private $dsn = "mysql:host=host;dbname=name_db";
- private $sql;
- private $DBH;
- function setSQL($sql){
- $this->sql = $sql; //if $sql is not set it troughs an error at PDOException
- }
- public function query()
- {
- //the connection will get established here if it hasn't been already
- if (is_null($this->DBH))
- try {
- $this->DBH = new PDO( $this->dsn, $this->username, $this->password );
- $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
- //query
- $result = $this->DBH->prepare($this->sql);
- $result->execute();
- return $result->fetch(PDO::FETCH_ASSOC);
- } catch(PDOException $e) {
- echo "I'm afraid I can't do that1.";
- //file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
- }
- }
- //clear connection and variables
- function __destruct(){
- $this->DBH = null;
- }
- }
- $sql = "SELECT * from stock WHERE id = 302";
- $test = new Connection();
- $test->setSQL($sql);
- echo $test->query();
- class ApplicationResourcePool
- {
- static var $_dbHandle;
- private static $_dbConfig = array(
- 'dsn' => '',
- 'username' => '',
- 'password' => '',
- );
- public static getDbHandle(){
- if(self::$_dbHandle == null){
- self::$_dbHandle = new PDO(
- self::$_dbConfig['dsn'] ,
- self::$_dbConfig['username'],
- self::$_dbConfig['password']
- );
- }
- return self::$_dbHandle;
- }
- }
- class StockMapper
- {
- protected $_dbh;
- public __construct($dbh = null)
- {
- if($dbh == null){
- $this->_dbh = ApplicationResourcePool::getDbHandle();
- } else {
- $this->_dbh = $dbh;
- }
- }
- public getStockById($stockId){
- $sth=$this->_dbh->prepare("SELECT * from stock WHERE id = :stockId");
- $sth->bindParam(":stockId", $stockId);
- $sth->execute();
- $result = $sth->fetch(PDO::FETCH_ASSOC);
- return $result[0];
- }
- }
- $stockMapper = new StockMapper();
- $stockData = $stockMapper->getStockById('302');
- SELECT * from stock WHERE id = ?
- array(302)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement