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"; // your host name
- private $username = "root"; // your user name
- private $password = ""; // your password
- private $db = "test_db"; // your database name
- 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"));
- }
- // this method used to execute mysql query
- 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") ; // there are pass two parameters one is table fields and second is table name
- echo "<pre>";
- print_r($a);
- echo "</pre>";
- ?>
Output:


Join the conversation! Your thoughts help the community grow.