0

I'm trying to substitute my old php code with PDO but I'm facing two main problems trying to do it.

First of all, let me show you my config script, where I connect the db:

<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

And my folder tree:

www/
├── A/
    ├── main/
    │    ├── test2.php
    ├── sys/
         ├── class/
         │     ├── test.php
         ├── config.php

Now, the first problem is that PDO works only if I put the require of config.php inside a function, like in this file, test.php:

<?php
function test(){

    require_once('../config.php');

    try {
        $sql = "SELECT count(*) FROM chats";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        return $number_of_rows = $stmt->fetchColumn();
    }

    $conn = null;
}
?>

//html is used only to show me if it works, it will be deleted from the final script
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>

        <?php print_r(test()); ?>

    </body>
</html>

And I think it's a problem because this file will have hundreds of functions and I will make it too dirty writing a require_once in every function, or is this the only way?

Now, the second problem is that even if test.php works, when I try to call the function inside it from test2.php, that is located in another folder, it doesn't show me anything anymore. This is the code inside test2.php:

<?php

include('../sys/class/test.php');

?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>

        <?php print_r(test()); ?>

    </body>
</html>

Any idea on how I can fix these two problems? Thank you very much anyway :)

0 Answers0