Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO error scope?

Tags:

php

mysql

pdo

I've been searching and testing different approaches to fix my issue but I still can't find the damn solution. I'm new to PHP and i'm trying to teach myself working with PDO.

db.php:

<?php

$dsn = 'mysql:myHost=localhost;dbname=ewt';
$user= 'root';
$pass = '';

try {
    $pdo = new PDO($dsn, $user, $pass);
    $pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

showCust.php

<?php

include_once('db.php');

try {


    $sql = "SELECT * FROM PERSOON";
    $result = $pdo->query($sql);
    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo $row['VOORNAAM']. ' - '. $row['NAAM']. ' - '. $row['EMAIL']. ' - '. $row['ADRES']. '<br />';
    }
    $pdo = null;
}
catch(PDOException $e) {
    echo $e->getMessage();
}

It works perfecty when I copy the db.php code in the showCust.php but I want to split the DB connection from every other file. I know it has to do something with the scope of $pdo but I just can't figure it out ...

The error i keep getting are:

Notice: Undefined variable: pdo ... line 9

Fatal error: Call to a member function query() on a non-object in ... line 9

I know the database does NOT have a pw. This is purely for test purposes.

Thanks in advance !

like image 692
user3511568 Avatar asked Apr 17 '26 10:04

user3511568


1 Answers

In essence, *_once functions in PHP are but a dirty trick. A crutch to help unsuspecting programmer to keep their code in order. But nothing goes for free.

This "once" behavior means you are running this function indeed once.
Means if you have included it once already, all the consequent calls will do... n o t h i n g.

Thus, if you used include_once for db.php earlier in the code and it was inside of a function, then $pdo variable remained local for that function, leaving global scope without $pdo variable. While when included next time, db.php weren't executed and thus you have got no $pdo at all.
However, it's just a speculation.

Other reasons could be various typos. Also make sure you are running exactly the same code you posted here. You'll be surprised by it's working flawlessly

like image 91
Your Common Sense Avatar answered Apr 19 '26 00:04

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!