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 ).

  1. class DatabaseClass
  2. {
  3. private $host = "localhost"; // your host name
  4. private $username = "root"; // your user name
  5. private $password = ""; // your password
  6. private $db = "test_db"; // your database name
  7. public
  8. function __construct()
  9. {
  10. mysql_connect($this - > host, $this - > username, $this - > password) or die(mysql_error("database"));
  11. mysql_select_db($this - > db) or die(mysql_error("database"));
  12. }
  13. // this method used to execute mysql query
  14. protected
  15. function query_executed($sql)
  16. {
  17. $c = mysql_query($sql);
  18. return $c;
  19. }
  20. public
  21. function get_rows($fields, $id = NULL, $tablename = NULL)
  22. {
  23. $cn = !emptyempty($id) ? " WHERE $id " : " ";
  24. $fields = !emptyempty($fields) ? $fields : " * ";
  25. $sql = "SELECT $fields FROM $tablename $cn";
  26. $results = $this - > query_executed($sql);
  27. $rows = $this - > get_fetch_data($results);
  28. return $rows;
  29. }
  30. protected
  31. function get_fetch_data($r)
  32. {
  33. $array = array();
  34. while ($rows = mysql_fetch_assoc($r))
  35. {
  36. $array[] = $rows;
  37. }
  38. return $array;
  39. }
  40. }

Step 2: Create index.php file,

  1. <?php
  2. include("DatabaseClass.php");
  3. $obj = new DatabaseClass ();
  4. $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
  5. echo "<pre>";
  6. print_r($a);
  7. echo "</pre>";
  8. ?>

Output: