4

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

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Durgaprasad
  • 157
  • 2
  • 6
  • 19

3 Answers3

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

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
2

The simplest way of doing it is to do the database connectivity in a separate file like "database.php and then you can include this file on every new page you are creating...eg if you are creating a page like "dothis.php". then at the top of your dothis.php page write a statement include_once ('/path/to/your/file/database.php'); then you can use your $db object in the whole file wherever you want.

Let me see
  • 5,063
  • 9
  • 34
  • 47
0

What you can do is to create a PHP file, let's say 'pdoconn.php'. In that file, prepare that $db object. Finally, for each of your PHP files, just include pdoconn.php at first. So, while your PHP files are being loaded, they will firstly connect to MySQL and give you the $db object.

tcak
  • 2,142
  • 1
  • 16
  • 23