How to call PDO in separate system file?

Asked

Viewed 664 times

1

I have a programming problem in which I put my PDO type connection in the header and I need that $pdo be called in any other system file. 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");

?>

Man conexao.php is this: PDO

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

I imagined that the fact of requires linking one file to the other would cause the $pdo travel to the footer but that’s not what happens. Then I have to call the file php connection. on the footer, which I imagine is about POG.

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

Updating

  • This is the only file I use to connect to the entire system, so the connection is not being closed. I will activate PHP errors.
  • 3

    Apparently that should work. It may be that the includes do not work on a certain page because of relative paths (and you have the warnings and errors turned off); it may be that you have something in your code closing the connection or preventing new queries from running; it may be several things, I find it difficult to answer with certainty only with the information you posted.

1 answer

2


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

Bench:

<?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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.