How to call the PDO on file other than the system?

1

I have a programming problem in which I put my PDO-type connection in the header and need to have $pdo called in any other file on the system. Example:

  

header.php

<?php require("configs/conexao.php"); ?>
  

index.php

<?php 

     require("header.php");
     // todo o conteúdo
     require("footer.php");

?>
  

footer.php

<?php 

     $consulta = $pdo->query("SELECT * FROM usuarios");

?>

My conexao.php is this: PDO

We can notice that I called the PDO connection in the header because this file will be present on every page of the system and I want to be able to make a select in the footer because there is a need to if you call some information there.

I figured the fact that requires to link one file to another would cause $pdo to travel to the footer but that is not the case. Then I have to call the connection.php file in the footer, which I imagine to be POG .

How can I then insert the connection file in the header and call the $pdo in the footer or any other file if the need exists?

  

Update

  • This is the only file I use to connect to the entire system, so the connection is not being closed. I'm going to enable PHP errors.
asked by anonymous 31.10.2014 / 18:48

1 answer

2

I did a test here and it worked perfectly. Try to run these scripts below:

Bank:

<?php

try {
    $dsn = 'mysql:dbname=loja;host=127.0.0.1';
    $user = 'root';
    $password = '';

    $objDb = new PDO($dsn, $user, $password);
    $objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


} catch (PDOException $e) {
    echo   $e->getMessage();
}

header.php

 <?php require("banco/conexaoPDO.php");

    ?>
 <head>
        <meta charset="ISO-8859-1">
        <title></title>
    </head>

footer.php

<?php

 $sql = "SELECT name FROM products"; 

   $result = $objDb->query($sql);

   if (!$result) {
        throw new PDOException('The execute massage failed ');
    }

  $result->setFetchMode(PDO::FETCH_ASSOC);

    $items = $result->fetchAll();

    foreach ( $items as  $item)
         echo "<br>" . $item['name'] . "<br>";

index.php

<!DOCTYPE html>

<html>
   <?php  
    require("header.php");
    ?>
    <body>

    </body>
     <?php require("footer.php");
      ?>
</html>
    
31.10.2014 / 20:04