php - Using PDO with other classes -


i have been forcing myself more oop. have hated in till now. when using simple prepare statment in pdo within class method never works. resolved doing obvious: globalising pdo object method. works, , want - if had many many methods loads of different classes, adding "global $db;" first line alllll functions/methods seems quite tedious. there way of integrating pdo classes? or @ least each class- instead of every single bloody method?

heres very simple example of what curretnly works, said tedious:

<?php  $db = new pdo("mysql:host=localhost;dbname=blaa;", "blaa", "blaa"); class test{  function show($col, $id){     global $db;     $result = $db->prepare("select ".$col." products id = :id");     $result->execute(array("id"=>$id));     $row = $result->fetch();     echo $row[$col]; } }  $show = new test(); $show->show("price", 1); ?> 

..so can use pdo in method "show()" if add method, have put "global $db;" in again...

so how not globalise in method, instead, classes? tried inheriting pdo class "test" class did not work; tried using constructor like:

<?php $db = new pdo("mysql:host=localhost;dbname=blaa;", "blaa", "blaa"); class test{     public $db; function __construct($db){            $this->db = $db;     } function show($col, $id){     $result = $db->prepare("select ".$col." products id = :id");     $result->execute(array("id"=>$id));     $row = $result->fetch();     echo $row[$col]; } }  $show = new test($db); $show->show("price", 1); ?> 

but did not work..

any appreciated!

thanks -wylie

$this->db = $db; 

means assigned $db $this->db, not contrary!

so, have use $this->db, not $db in class

$result = $this->db->prepare("select ".$col." products id = :id"); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -