Hello,
I’m in the process of learning OOP and have a few questions with the simple example i’m trying to use to query the table ‘test’ that I was hoping someone could help me with as I have a few questions before I can move on that i’d really like to understand.
-
I’ve created a constructor, but for some reason my page outputs a mysql_connect() message, almost like the public attributes have not been passed to the construct method. I’ve double checked the details and they are all fine. Anyone see any issues?
-
In my class Database I have my attributes defined as ‘private’. Is that right? What i’m basically thinking here is that my class Database will hold all database queries, so they would be no need to make them public or protected right?
-
Does every class I create in my system need a construct method. Ie a general rule whenever you create a class nomatter what it is start with a constructor method?
-
You don’t really need a destructor method in your classes unless you are doing something like closing a database connection ie with my below above?
-
In my method query() I echo back a message with css styling. Is there any kind of general unwritten rule which says styling should be set outside the class in CSS?
<?php
class Database {
private $host;
private $username;
private $password;
private $database;
function __construct() {
$conn = mysql_connect($this->host,$this->username,$this->password);
mysql_select_db ($this->database,$conn) or die (mysql_error());
}
function query() {
$SQL = "SELECT * from test";
$QUE = mysql_query($SQL) or die (mysql_error());
while($RES = mysql_fetch_array($QUE)) {
echo "". $RES['id']."<br />";
echo "". $RES['name']."";
}
}
function __destruct() {
mysql_close($conn);
}
}
//Create an instance of the class Database
$conn = new Database;
// and run the connect method to connect to database
$conn->host = "localhost";
$conn->username = "***********";
$conn->password = "*****";
$conn->database = "************";
//Now grab that data from the table
$conn->query();
?>