Advertisement
Guest User

Untitled

a guest
May 15th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.77 KB | None | 0 0
  1. filename: myaccesspdo.cls.php
  2.  
  3. <?php
  4. /**
  5. * Classe per la gestione delle funzionalita' base del db mediante i PDO
  6. * Class to manage basic DB functions through PDO
  7. *
  8. * @author Alessandro Conti
  9. * @version 0.2b
  10. * @copyright mbuti corporation & sons
  11. */
  12. class MyAccessPDO extends PDO {
  13.  
  14. // private $dbh;//pdo class link
  15. private $dbInfo = array();
  16. private $enableError = true; //flag to enable pdo error logging
  17. public $enableLog = true;
  18. public $result; //last query result
  19. public $lastQuery;
  20. private $err;
  21. private $log;
  22.  
  23.  
  24. /**
  25. * Works with MySQL and PostgreSQL
  26. *
  27. * @param unknown_type $host
  28. * @param unknown_type $dbname
  29. * @param unknown_type $user
  30. * @param unknown_type $pass
  31. * @param unknown_type $dbType
  32. */
  33. public function __construct($host, $dbname, $user, $pass, $dbType='mysql'){
  34. try {
  35. parent::__construct("$dbType:host=$host;dbname=$dbname", $user, $pass);
  36. $this->dbInfo['$host'] = $host;
  37. $this->dbInfo['$dbname'] = $dbname;
  38. $this->dbInfo['$user'] = $user;
  39. $this->dbInfo['$pass'] = $pass;
  40. $this->dbInfo['$dbType'] = $dbType;
  41.  
  42. $this->logEvent(" Inside __construct ;\n classe PDO ".print_r($this,true)." params connection : ".print_r($this->dbInfo,true));
  43.  
  44. if ($this->enableError) {
  45. $this->displayError();
  46. $this->logEvent(" enable error view ");
  47. }
  48.  
  49. } catch (PDOException $e) {
  50. echo "<br /> Error!: " . $e->getMessage() . "\n";
  51. echo "<pre>";
  52. print_r($e);
  53. echo "</pre>";
  54.  
  55. }
  56. }
  57.  
  58. /**
  59. * Abilita la visuizzazione degli errori dettagliati PDO
  60. * Enables PDO detailed errors reporting
  61. *
  62. */
  63. public function displayError(){
  64. try {
  65. parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  66. } catch (PDOException $e) {
  67. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  68. }
  69. }
  70.  
  71. /**
  72. * Initiates a transaction
  73. *
  74. * @return bool
  75. */
  76. public function beginTransaction() {
  77. return parent::beginTransaction();
  78. }
  79.  
  80. /**
  81. * Commits a transaction
  82. *
  83. * @return bool
  84. */
  85. public function commit() {
  86. return parent::commit();
  87. }
  88.  
  89. /**
  90. * Rolls back a transaction
  91. *
  92. * @return bool
  93. */
  94. public function rollBack() {
  95. return parent::rollBack();
  96. }
  97.  
  98. /**
  99. * PDO error code
  100. *
  101. * @return unknown
  102. */
  103. public function getErrorCode(){
  104. return parent::errorCode();
  105. }
  106.  
  107. /**
  108. * PDO error info
  109. *
  110. * @return unknown
  111. */
  112. public function getErrorInfo(){
  113. return parent::errorInfo();
  114. }
  115.  
  116. /**
  117. * Esegue una query facendo il binding con i valori presenti nell'array dei paramentri
  118. *
  119. *
  120. * es : $myDb->prepare('SELECT * from programmattori WHERE nome = ?',array('giggighe'));
  121. * es : $myDb->prepare('SELECT * from programmattori WHERE nome = :cccc',array(':cccc'=>'giggighe'))
  122. * @param unknown_type $query
  123. * @param unknown_type $bindArrParams
  124. * @return unknown
  125. */
  126. /*public function prepare($query,$bindArrParams){
  127. try {
  128. $this->lastQuery = $query;
  129. $sth = parent::prepare($query);
  130. $key = array_keys($bindArrParams);
  131. $this->logEvent("dentro prepare ; \n query : $query \n parametri : ".print_r($bindArrParams,true));
  132.  
  133. // Verifico come inizia la chiave del primo elemento
  134. // First element key starts with...
  135. if (!is_numeric($key[0]) && (substr($key[0],0,1)==':')){
  136. // Parametri individuati da :parametro
  137. // ... starts with :
  138. foreach ($bindArrParams as $keyParams => $valueParams){
  139. $this->logEvent(" Binding del parametro $keyParams col valore $valueParams");
  140. $sth->bindParam($keyParams,$valueParams);
  141. $sth->execute();
  142. }
  143. } else {
  144. $this->logEvent(" Binding dei parametri ".print_r($bindArrParams,true));
  145. // Parametri individuati da ?
  146. // ... starts with ?
  147. $sth->execute($bindArrParams);
  148. }
  149.  
  150. $this->logEvent(" valore dello statment ".print_r($sth,true));
  151. $this->result = $sth->fetchAll();
  152. $sth->closeCursor();// sblocco stment
  153. $this->logEvent("result vale : {$this->result}");
  154.  
  155. return $this->result;
  156.  
  157. } catch (PDOException $e) {
  158. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  159. }
  160. }*/
  161.  
  162. /**
  163. * Executes query and returns an array containing resulting items based on parameter $mode
  164. *
  165. * Valori possibili parametro $mode
  166. * Possible values of parameter $mode
  167. * FETCH_NUM Numero colonna - column number
  168. * FETCH_ASSOC Array associativo - associative array
  169. * FETCH_OBJ Array oggetto - object array
  170. * FETCH_BOTH Array con nomi colonne e numeri!! - associative array with both column names and column numbers
  171. *
  172. * @param unknown_type $query
  173. * @param parametro per stabilire la modalita' come deve essere l'array risultato $mode - fetch mode $mode
  174. */
  175.  
  176. public function fetchRow($query,$mode = PDO::FETCH_BOTH){
  177. try {
  178. $this->lastQuery = $query;
  179. $stmt = parent::query($query);
  180.  
  181. //*** Array risultato
  182. // Resulting array
  183. $this->result = $stmt->fetchAll($mode);
  184. $this->logEvent("dentro fetchRow ; \n query : $query \n mode : $mode \n result : ".print_r($this->result,true))." \n stm :".print_r($stmt,true);
  185. return $this->result;
  186. } catch (PDOException $e) {
  187. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  188. }
  189. }
  190.  
  191. /**
  192. * Funzione per eseguire query da utilizzarsi per insert, update e delete
  193. * Executes insert, update and delete
  194. *
  195. * @param unknown_type $query
  196. */
  197. public function simpleQuery($query){
  198. try {
  199. $this->lastQuery = $query;
  200. $count = parent::exec($query);
  201. $this->logEvent("inside simpleQuery ; \n query : $query \n count : $count \n ");
  202.  
  203. return $count;
  204. } catch (PDOException $e) {
  205. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  206. }
  207. }
  208.  
  209.  
  210. /**
  211. * Ritorna last insert id su una sequence: la sequenza
  212. * Returns last insert id of a sequence
  213. * es : $myDb->lastInsertId("user_id_seq");
  214. *
  215. * @param unknown_type $name
  216. * @return unknown
  217. */
  218. public function lastInsertId($name=''){
  219. try {
  220. $id = parent::lastInsertId($name);
  221. //$this->logEvent("dentro lastInsertId ; \n last query : {$this->lastQuery} \n count : $count \n last insert id $id \n sequence name : $name");
  222. return $id;
  223.  
  224. } catch (PDOException $e) {
  225. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  226. }
  227. }
  228.  
  229. public function closeConnection(){
  230. try {
  231. $this->logEvent("dentro closeConnection ; \n ");
  232. // $this->dbh = null;
  233. } catch (PDOException $e) {
  234. $this->logErr(__FUNCTION__." Error!: " . $e->getMessage() . "\n", $e);
  235. }
  236. }
  237.  
  238. /**
  239. * Funzione di tracciamento
  240. * Trace function
  241. *
  242. * @param unknown_type $str
  243. */
  244. public function logEvent($str){
  245. if ($this->enableLog){
  246. $this->log.= "\n".date(("Ymd H:i:s"))."-->".$str."<--";
  247. }
  248. }
  249.  
  250. /**
  251. * Funzione di tracciamento degli errori
  252. * Error tracing function
  253. *
  254. * @param Stringa errore $str
  255. * @param Eccezione $e
  256. */
  257. public function logErr($str,$e){
  258. $this->err.= "\n".date(("Ymd H:i:s"))."-->".$str."<--";
  259. echo "<br /> $this->err";
  260. // lancio eccezione
  261. throw new PDOException($e);
  262. }
  263.  
  264. /**
  265. * Ritorna la lista di errori che si sono verificati
  266. * Returns errors list
  267. *
  268. * @return unknown
  269. */
  270. public function getError(){
  271. return "Err : ".$this->err.";\n getErrorInfo ".print_r($this->getErrorInfo(),true)."; \n getErrorCode : ".print_r($this->getErrorCode(),true);
  272. }
  273.  
  274. /**
  275. * Ritorna la stringa del tracciamento di tutte le operazioni
  276. * Returns a string containing logs
  277. *
  278. * @return log
  279. */
  280. public function getLog(){
  281. return $this->log;
  282. }
  283.  
  284. }
  285.  
  286. /**
  287. * Singleton mydb
  288. *
  289. */
  290. class mydb{
  291.  
  292. // instanza di myAccessPDO
  293. // class private instance
  294. private static $instance = NULL;
  295.  
  296. // Costruttore privato
  297. // private constructor
  298. private function __construct() {
  299. /*** maybe set the db name here later ***/
  300. }
  301.  
  302. /**
  303. *
  304. * Return DB instance or create intitial connection
  305. *
  306. * @return object (PDO)
  307. *
  308. * @access public
  309. *
  310. */
  311. public static function getInstance() {
  312.  
  313. if (!self::$instance) {
  314. self::$instance = new myAccessPDO('localhost','db1','postgres','postgres','pgsql');
  315. }
  316. return self::$instance;
  317. }
  318.  
  319. private function __clone(){
  320. }
  321.  
  322. }
  323.  
  324.  
  325. ?>
  326.  
  327. usage:
  328.  
  329. // Localhost
  330. $db_server = "mysql";
  331. $db_host = "localhost";
  332. $db_user = "root";
  333. $db_pass = "f00b4r";
  334. $db_name = "findbodz";
  335.  
  336. require_once("myaccesspdo.cls.php");
  337.  
  338. $dbconn = new myAccessPDO($db_host,$db_name,$db_user,$db_pass,$db_server);
  339.  
  340. $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";
  341. $result = $dbconn->fetchRow($sql, PDO::FETCH_ASSOC);
  342.  
  343. foreach($result as $row) {
  344. echo $row['adtitle'] . " " . $row['addesc'] . " " . $row['email'] . " " . $row['ip'] . "<BR>";
  345. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement