How to set up a database connection, using Object-Oriented Programming (OOP), PHP and MySQL. Below following step:
Step 1: To create files DatabaseClass.php and write a class with a function( query_executed,get_rows,get_fetch_data ).
- class DatabaseClass
- {
- private $host = "localhost";
- private $username = "root";
- private $password = "";
- private $db = "test_db";
- public
- function __construct()
- {
- mysql_connect($this - > host, $this - > username, $this - > password) or die(mysql_error("database"));
- mysql_select_db($this - > db) or die(mysql_error("database"));
- }
-
- protected
- function query_executed($sql)
- {
- $c = mysql_query($sql);
- return $c;
- }
- public
- function get_rows($fields, $id = NULL, $tablename = NULL)
- {
- $cn = !emptyempty($id) ? " WHERE $id " : " ";
- $fields = !emptyempty($fields) ? $fields : " * ";
- $sql = "SELECT $fields FROM $tablename $cn";
- $results = $this - > query_executed($sql);
- $rows = $this - > get_fetch_data($results);
- return $rows;
- }
- protected
- function get_fetch_data($r)
- {
- $array = array();
- while ($rows = mysql_fetch_assoc($r))
- {
- $array[] = $rows;
- }
- return $array;
- }
- }
Step 2: Create index.php file,
- <?php
- include("DatabaseClass.php");
- $obj = new DatabaseClass ();
- $a = $obj-> get_rows (implode(",",array("ID","post_date","post_title")), '' , "tablenane") ;
- echo "<pre>";
- print_r($a);
- echo "</pre>";
- ?>
Output: