3

I want to share a MySQL connection, with other class within PHP, which held the query to do. So MySQL.php contains:

    <?php
$user = 'username';
$passowrd = 'password';
$conn = new PDO('mysql:host=ip;dbname=DBName;port=3306',$user,$passowrd);
?>

And the php file, which I call MyLibrary.php contains:

    <?php
include 'DB.php';

class Manager {

    function jsonQuery() {

        $response = array ();


        $st = $conn->query ( "query");

        $response ["results"] = array ();

        foreach ( $st->fetchAll () as $row ) {

            //my stuff with the query
        }

        $response ["success"] = 1;

        echo json_encode ( $response );
    }

}

$object = new Manager();

$object->jsonQuery();

?>

So how can I do ?

I love coding
  • 1,183
  • 3
  • 18
  • 47
  • You don't want to keep the database connection open and share it across different modules of your project. Instead you include the file that opens the database (i.e. `MySQL.php`) wherever you need database access and close it after your queries. – Haensl Jul 02 '15 at 12:35
  • You can make a class for the connect that have a variable, maybe a controller, and then always extend that. Just remember to make a __construct in the controller that makes the variable to the PDO connection – Jesper Jul 02 '15 at 12:36
  • I believe what you are after is something called the [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern), but could equally be done with a static class. – Phylogenesis Jul 02 '15 at 12:36

2 Answers2

3

It's called dependency injection and it's simple to implement. You pass the parameter into your class directly when you instantiate it. This way you never implement it more than once and you share that instance across your codebase

class Manager {
    /** @var \PDO */
    protected $pdo;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function jsonQuery() {
        $response = array ();
        $st = $this->pdo->query("query");
        $response ["results"] = array();

        foreach ( $st->fetchAll() as $row ) {
            //my stuff with the query
        }

        $response ["success"] = 1;
        echo json_encode($response);
    }
}

$object = new Manager($conn);
Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
0

I think the best way is to use a function, it is allways global :-)

Simple sample:

function &pdo() {
  $user = 'username';
  $passowrd = 'password';
  static $db = null;
  if($db===null)
    $db = new PDO('mysql:host=ip;dbname=DBName;port=3306',$user,$passowrd);
  return $db;
}

Alternative, but not good: use global:

function foo() {
  global $conn;
  # your code ....
}

or

$GLOBALS['conn'];

It is allways present.

Frank
  • 1,901
  • 20
  • 27