Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use PDO connection object in different files [duplicate]

Tags:

oop

php

mysql

pdo

Hello i am new to PDO with MYSQL, here are my two files 1) index.php

require_once 'prd.php';
try{
    $db = new PDO ('mysql:host=xxxx;dbname=xxx;charset=utf8', 'xxx', 'xxxx');
    echo 'connectd';
}catch(PDOException $conError){
    echo 'failed to connect DB' . $conError->getMessage ();
}
$conn = new prdinfo();
$conn->con($db);

2) product.php

class prdinfo{function con($db){
    try{
        foreach($db->query("select * from products where vendor_id = 2" ) as $row){
            $prod_id = $row ['product_id'];
            echo '<br/>' . $prod_id;
        }
    }catch(PDOException $ex){
        echo 'an error occured' . $ex->getMessage();
    }
}
}

my problem is here i can pass the connection object to every file, but i have so many files to use database queries, so i need to pass the $bd to all the files. this is getting burden on the code. so is there any way to connect the database with PDO. Thanks

like image 506
Durgaprasad Avatar asked Mar 22 '23 03:03

Durgaprasad


1 Answers

  1. pdo.php, taken from here. People often overlook many important connection options, so I had to write a dedicated article that explains how to connect with PDO properly

  2. product.php

     <?php
     class prdinfo  
     { 
         function __construct($db)
         {
             $this->db = $db;
         }
    
         function getVendor($vendor)
         {
             $sql = "select * from products where vendor_id = ?";
             $stm = $this->db->prepare($sql);
             $stm->execute(array($vendor));
             return $stm->fetchAll();
         }
     }
    
  3. index.php

     <?php
     require 'pdo.php';
     require 'product.php';
    
     $info   = new prdinfo($pdo);
     $vendor = $info->getVendor(2);
     foreach ($vendor as $row)
     {
         echo $row['product_id'];
     }
    

It would be also a good idea to implement class autoloading instead of manually calling require.

like image 164
Your Common Sense Avatar answered Apr 25 '23 16:04

Your Common Sense