Guest User

Untitled

a guest
Sep 16th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. PHP PDO-MYSQL : How to use database connection across different classes
  2. class connection{
  3.  
  4. private $host = 'localhost';
  5. private $dbname = 'devac';
  6. private $username = 'root';
  7. private $password ='';
  8.  
  9. public $con = '';
  10.  
  11. function __construct(){
  12.  
  13. $this->connect();
  14.  
  15. }
  16.  
  17. function connect(){
  18.  
  19. try{
  20.  
  21. $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
  22. $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  23.  
  24.  
  25. }catch(PDOException $e){
  26.  
  27. echo 'We're sorry but there was an error while trying to connect to the database';
  28. file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
  29.  
  30. }
  31. }
  32. }
  33.  
  34. class account_info{
  35.  
  36.  
  37. function getAccountInfo(){
  38.  
  39. $acc_info = $this->con->prepare("SELECT * FROM account_info");
  40. $acc_info->execute();
  41.  
  42. $results = $acc_info->fetchAll(PDO::FETCH_OBJ);
  43.  
  44. foreach ($results as $key) {
  45. $results->owner_firstname;
  46.  
  47. }
  48. }
  49.  
  50.  
  51. }
  52.  
  53. include_once 'classes/connection.class.php';
  54. include_once 'classes/accountinfo.class.php';
  55.  
  56. $con = new connection();
  57. $info = new account_info();
  58. $info->getAccountInfo();
  59.  
  60. $con = new connection();
  61. $info = new account_info();
  62.  
  63. $info = new account_info();
  64.  
  65. class account_info {
  66.  
  67. private $con;
  68.  
  69. public function __construct(connection $con) {
  70. $this->con = $con->con;
  71. }
  72.  
  73. public function getAccountInfo(){
  74.  
  75. $acc_info = $this->con->prepare("SELECT * FROM account_info");
  76. $acc_info->execute();
  77.  
  78. $results = $acc_info->fetchAll(PDO::FETCH_OBJ);
  79.  
  80. foreach ($results as $key) {
  81. $results->owner_firstname;
  82. }
  83. }
  84.  
  85. }
  86.  
  87. include_once 'classes/connection.class.php';
  88. include_once 'classes/accountinfo.class.php';
  89.  
  90. $con = new connection();
  91. $info = new account_info($con);
  92. $info->getAccountInfo();
  93.  
  94. class connection {
  95.  
  96. private static $hInstance;
  97.  
  98. public static function getInstance() {
  99. if (!(self::$hInstance instanceof self)) {
  100. self::$hInstance = new self();
  101. }
  102.  
  103. return self::$hInstance;
  104. }
  105.  
  106. /* your code */
  107. }
  108.  
  109. $database = connection::getInstance();
  110. $database->con->prepare(....)
Add Comment
Please, Sign In to add comment