Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. <?php
  2. require_once 'config.php'; // Database setting constants [DB_HOST, DB_NAME, DB_USERNAME, DB_PASSWORD]
  3. class dbHelper {
  4. private $db;
  5. private $err;
  6. function __construct() {
  7. $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
  8. try {
  9. $this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  10. } catch (PDOException $e) {
  11. $response["status"] = "error";
  12. $response["message"] = 'Connection failed: ' . $e->getMessage();
  13. $response["data"] = null;
  14. exit;
  15. }
  16. }
  17.  
  18.  
  19. function select($table, $where){
  20. try{
  21. $a = array();
  22. $w = "";
  23. foreach ($where as $key => $value) {
  24. $w .= " and " .$key. " like :".$key;
  25. $a[":".$key] = $value;
  26. }
  27. $stmt = $this->db->prepare("select * from ".$table." where 1=1 ". $w);
  28. $stmt->execute($a);
  29. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  30. if(count($rows)<=0){
  31. $response["status"] = "warning";
  32. $response["message"] = "No data found.";
  33. }else{
  34. $response["status"] = "success";
  35. $response["message"] = "Data selected from database";
  36. }
  37. $response["data"] = $rows;
  38. }catch(PDOException $e){
  39. $response["status"] = "error";
  40. $response["message"] = 'Select Failed: ' .$e->getMessage();
  41. $response["data"] = null;
  42. }
  43. return $response;
  44. }
  45. }
  46.  
  47. <?php
  48. /**
  49. * Database configuration
  50. */
  51. define('DB_USERNAME', 'root');
  52. define('DB_PASSWORD', '');
  53. define('DB_HOST', 'localhost');
  54. define('DB_NAME', 'database1');
  55.  
  56. ?>
  57.  
  58. <?php
  59. require_once 'dbHelper.php';
  60. $db = new dbHelper();
  61.  
  62. $rows = $db->select("customers_php",array());
  63. print_r(json_encode($rows,JSON_NUMERIC_CHECK));
  64. ?>
  65.  
  66. if($db_name == 'database1')
  67. {
  68. //#----------open database connection --------------------> TESTING
  69. $db_host = "localhost";
  70. $db_user = "root";
  71. $db_password = "";
  72. $db_name = "database1";
  73. }
  74.  
  75. if($db_name == 'database2')
  76. {
  77. //#----------open database connection --------------------> TESTING
  78. $db_host = "localhost";
  79. $db_user = "root";
  80. $db_password = "";
  81. $db_name = "database2";
  82. }
  83.  
  84. <?php
  85. require_once 'dbHelper.php';
  86. $db = new dbHelper();
  87.  
  88. //function select($dbname, $table, $where)......................
  89.  
  90. $rows = $db->select("database1","customers_php",array());
  91. print_r(json_encode($rows,JSON_NUMERIC_CHECK));
  92. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement