November 8, 201213 yr Hi all, is it good practice to echo information inside a class or not, the reason i ask is i am doing my best to lean OOP and i can connect to a database no problem but seem to have difficulty selecting rows example below <?php class Db { private $_host = "********"; private $_username = "********"; private $_password = "********"; private $_database = "********"; public function __construct() { if(mysql_connect($this->_host,$this->_username,$this->_password)) { echo "connection successfully<br />"; } if(mysql_select_db($this->_database)) { echo "database connected<br />"; } } public function select($query, $tableName) { $select=mysql_query("SELECT $query FROM $tableName")or die(mysql_error()); while($row=mysql_fetch_object($select)) { $row->page; } } } ?> <?php $db= new Db; $db->select("*", "page"); //foreach loop goes here ?> if i echo $row->page; inside the while loop it works but i would like to echo the information using a foreach loop outside the class Thank you
November 8, 201213 yr Author Sorted this <?php class DB { private $_host = "********"; private $_username = "********"; private $_password = "********"; private $_database = "********"; private $conn; public function __construct(){ $this->conn = mysql_connect($this->_host,$this->_username,$this->_password) or die(mysql_error()); mysql_select_db($this->_database) or die(mysql_error()); } public function select($table_name){ return mysql_query("SELECT * FROM ".$table_name, $this->conn); } } $Db = new DB; $results = $Db->select('page'); while ($row = mysql_fetch_object($results)) { echo "<p>" . $row->page. $row->title ."</p>"; } ?> Edited November 8, 201213 yr by ELITE
November 8, 201213 yr Author Why are you using the mysql_ set of functions because thats the way tutorial i have been looking at do it, ive only been trying with OOP 2 weeks and spend an hour or so each night trying improve, if there is a better way let me know, do you go in the Potters then
November 8, 201213 yr because thats the way tutorial i have been looking at do it, ive only been trying with OOP 2 weeks and spend an hour or so each night trying improve, if there is a better way let me know, do you go in the Potters then you need to look at the date of whatever tutorials your using and use mysqli or PDO
November 9, 201213 yr Author you need to look at the date of whatever tutorials your using and use mysqli or PDO Will Do thanks
Create an account or sign in to comment