Creating the database class file
Here we are going to create a simple class file for carrying database functions.
Here we are going to create a simple class file for carrying database functions.
- Open stupid>>include directory.
- create file and name it as 'database_class.php'.
<?php class Database { var $connection; function __construct() { $conn=@mysql_connect(DB_HOST,DB_USER,DB_PASS); if(!$conn) { die("Cannot connect to database"); } else { $this->connection=$conn; $this->select_db(DB_NAME); //echo "connected"; } } /************************** select db ***************************/ private function select_db($db) { if(!@mysql_select_db($db,$this->connection)) { die("Cannot select database"); } else { //echo "yes I GOT IT!!!"; } } /**************************** QUERY *******************************/ public function query($sql) { $result=@mysql_query($sql,$this->connection); if(!$result) { die("SQL Error"); } else { return $result; } } /***************************** fetch object *******************************/ public function fetch_obj($result) { return mysql_fetch_object($result); } public function fetch_array($result) { return mysql_fetch_array($result); } /****************************** fetch number ****************************/ public function fetch_num($result) { return mysql_num_rows($result); } } ?>Lets have a quick look at the functions (methods) used.
1] __construct()
There is no need of talking much about the constructor.This function is automatically called during class instantiation.In the constructor we are making a connection to database.The arguments in @mysql_connect() function are constants we defined in our 'base.php' file.If connection is established ,database is selected by calling the select_db method.
2] select_db()
This method selects the database
3] query()
To do a mysql query and return a result.
4]fetch_object(),fetch_array()
Both these methods have an argument which is usually the result returned from the query method.The former returns the result as an object,the latter as an array.
5]fetch_num()
This method is used to return the number of rows affected.
THIS IS A SIMPLE CLASS FILE AND NOT AN ADVANCED DATABASE CLASS FILE .
But you can use this for simple database operations.
The class instantiation will look like
$db= new Database();We will instantiate all our class files in a single file.I just mentioned it as an example.So if we need to call any method in database class, we will use '->'
for example, to do a query ,
$db->query("YOUR-QUERY-HERE");In the next post we will have a look at our next class file 'theme_class.php' to handle themes.
<<<PREVIOUS || NEXT>>>
0 comments:
Post a Comment