Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- filename: myaccesspdo.cls.php
- <?php
- /**
- * Classe per la gestione delle funzionalita' base del db mediante i PDO
- * Class to manage basic DB functions through PDO
- *
- * @author Alessandro Conti
- * @version 0.2b
- * @copyright mbuti corporation & sons
- */
- class MyAccessPDO extends PDO {
- // private $dbh;//pdo class link
- private $dbInfo = array();
- private $enableError = true; //flag to enable pdo error logging
- public $enableLog = true;
- public $result; //last query result
- public $lastQuery;
- private $err;
- private $log;
- /**
- * Works with MySQL and PostgreSQL
- *
- * @param unknown_type $host
- * @param unknown_type $dbname
- * @param unknown_type $user
- * @param unknown_type $pass
- * @param unknown_type $dbType
- */
- public function __construct($host, $dbname, $user, $pass, $dbType='mysql'){
- try {
- parent::__construct("$dbType:host=$host;dbname=$dbname", $user, $pass);
- $this->dbInfo['$host'] = $host;
- $this->dbInfo['$dbname'] = $dbname;
- $this->dbInfo['$user'] = $user;
- $this->dbInfo['$pass'] = $pass;
- $this->dbInfo['$dbType'] = $dbType;
- $this->logEvent(" Inside __construct ;\n classe PDO ".print_r($this,true)." params connection : ".print_r($this->dbInfo,true));
- if ($this->enableError) {
- $this->displayError();
- $this->logEvent(" enable error view ");
- }
- } catch (PDOException $e) {
- echo "<br /> Error!: " . $e->getMessage() . "\n";
- echo "<pre>";
- print_r($e);
- echo "</pre>";
- }
- }
- /**
- * Abilita la visuizzazione degli errori dettagliati PDO
- * Enables PDO detailed errors reporting
- *
- */
- public function displayError(){
- try {
- parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }
- /**
- * Initiates a transaction
- *
- * @return bool
- */
- public function beginTransaction() {
- return parent::beginTransaction();
- }
- /**
- * Commits a transaction
- *
- * @return bool
- */
- public function commit() {
- return parent::commit();
- }
- /**
- * Rolls back a transaction
- *
- * @return bool
- */
- public function rollBack() {
- return parent::rollBack();
- }
- /**
- * PDO error code
- *
- * @return unknown
- */
- public function getErrorCode(){
- return parent::errorCode();
- }
- /**
- * PDO error info
- *
- * @return unknown
- */
- public function getErrorInfo(){
- return parent::errorInfo();
- }
- /**
- * Esegue una query facendo il binding con i valori presenti nell'array dei paramentri
- *
- *
- * es : $myDb->prepare('SELECT * from programmattori WHERE nome = ?',array('giggighe'));
- * es : $myDb->prepare('SELECT * from programmattori WHERE nome = :cccc',array(':cccc'=>'giggighe'))
- * @param unknown_type $query
- * @param unknown_type $bindArrParams
- * @return unknown
- */
- /*public function prepare($query,$bindArrParams){
- try {
- $this->lastQuery = $query;
- $sth = parent::prepare($query);
- $key = array_keys($bindArrParams);
- $this->logEvent("dentro prepare ; \n query : $query \n parametri : ".print_r($bindArrParams,true));
- // Verifico come inizia la chiave del primo elemento
- // First element key starts with...
- if (!is_numeric($key[0]) && (substr($key[0],0,1)==':')){
- // Parametri individuati da :parametro
- // ... starts with :
- foreach ($bindArrParams as $keyParams => $valueParams){
- $this->logEvent(" Binding del parametro $keyParams col valore $valueParams");
- $sth->bindParam($keyParams,$valueParams);
- $sth->execute();
- }
- } else {
- $this->logEvent(" Binding dei parametri ".print_r($bindArrParams,true));
- // Parametri individuati da ?
- // ... starts with ?
- $sth->execute($bindArrParams);
- }
- $this->logEvent(" valore dello statment ".print_r($sth,true));
- $this->result = $sth->fetchAll();
- $sth->closeCursor();// sblocco stment
- $this->logEvent("result vale : {$this->result}");
- return $this->result;
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }*/
- /**
- * Executes query and returns an array containing resulting items based on parameter $mode
- *
- * Valori possibili parametro $mode
- * Possible values of parameter $mode
- * FETCH_NUM Numero colonna - column number
- * FETCH_ASSOC Array associativo - associative array
- * FETCH_OBJ Array oggetto - object array
- * FETCH_BOTH Array con nomi colonne e numeri!! - associative array with both column names and column numbers
- *
- * @param unknown_type $query
- * @param parametro per stabilire la modalita' come deve essere l'array risultato $mode - fetch mode $mode
- */
- public function fetchRow($query,$mode = PDO::FETCH_BOTH){
- try {
- $this->lastQuery = $query;
- $stmt = parent::query($query);
- //*** Array risultato
- // Resulting array
- $this->result = $stmt->fetchAll($mode);
- $this->logEvent("dentro fetchRow ; \n query : $query \n mode : $mode \n result : ".print_r($this->result,true))." \n stm :".print_r($stmt,true);
- return $this->result;
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }
- /**
- * Funzione per eseguire query da utilizzarsi per insert, update e delete
- * Executes insert, update and delete
- *
- * @param unknown_type $query
- */
- public function simpleQuery($query){
- try {
- $this->lastQuery = $query;
- $count = parent::exec($query);
- $this->logEvent("inside simpleQuery ; \n query : $query \n count : $count \n ");
- return $count;
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }
- /**
- * Ritorna last insert id su una sequence: la sequenza
- * Returns last insert id of a sequence
- * es : $myDb->lastInsertId("user_id_seq");
- *
- * @param unknown_type $name
- * @return unknown
- */
- public function lastInsertId($name=''){
- try {
- $id = parent::lastInsertId($name);
- //$this->logEvent("dentro lastInsertId ; \n last query : {$this->lastQuery} \n count : $count \n last insert id $id \n sequence name : $name");
- return $id;
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }
- public function closeConnection(){
- try {
- $this->logEvent("dentro closeConnection ; \n ");
- // $this->dbh = null;
- } catch (PDOException $e) {
- $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
- }
- }
- /**
- * Funzione di tracciamento
- * Trace function
- *
- * @param unknown_type $str
- */
- public function logEvent($str){
- if ($this->enableLog){
- $this->log.= "\n".date(("Ymd H:i:s"))."-->".$str."<--";
- }
- }
- /**
- * Funzione di tracciamento degli errori
- * Error tracing function
- *
- * @param Stringa errore $str
- * @param Eccezione $e
- */
- public function logErr($str,$e){
- $this->err.= "\n".date(("Ymd H:i:s"))."-->".$str."<--";
- echo "<br /> $this->err";
- // lancio eccezione
- throw new PDOException($e);
- }
- /**
- * Ritorna la lista di errori che si sono verificati
- * Returns errors list
- *
- * @return unknown
- */
- public function getError(){
- return "Err : ".$this->err.";\n getErrorInfo ".print_r($this->getErrorInfo(),true)."; \n getErrorCode : ".print_r($this->getErrorCode(),true);
- }
- /**
- * Ritorna la stringa del tracciamento di tutte le operazioni
- * Returns a string containing logs
- *
- * @return log
- */
- public function getLog(){
- return $this->log;
- }
- }
- /**
- * Singleton mydb
- *
- */
- class mydb{
- // instanza di myAccessPDO
- // class private instance
- private static $instance = NULL;
- // Costruttore privato
- // private constructor
- private function __construct() {
- /*** maybe set the db name here later ***/
- }
- /**
- *
- * Return DB instance or create intitial connection
- *
- * @return object (PDO)
- *
- * @access public
- *
- */
- public static function getInstance() {
- if (!self::$instance) {
- self::$instance = new myAccessPDO('localhost','db1','postgres','postgres','pgsql');
- }
- return self::$instance;
- }
- private function __clone(){
- }
- }
- ?>
- usage:
- // Localhost
- $db_server = "mysql";
- $db_host = "localhost";
- $db_user = "root";
- $db_pass = "f00b4r";
- $db_name = "findbodz";
- require_once("myaccesspdo.cls.php");
- $dbconn = new myAccessPDO($db_host,$db_name,$db_user,$db_pass,$db_server);
- $sql = "SELECT adtitle, addesc, an.email, an.ip FROM ads a INNER JOIN ad_detail ad ON a.adid=ad.adid INNER JOIN anons an ON ad.posterid = an.anonid";
- $result = $dbconn->fetchRow($sql, PDO::FETCH_ASSOC);
- foreach($result as $row) {
- echo $row['adtitle'] . " " . $row['addesc'] . " " . $row['email'] . " " . $row['ip'] . "<BR>";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement