Tuesday, 28 August 2018

PHP PDO Fetch_Assoc does not return correctly

I have searched, and maybe I am searching for the wrong thing, but I need help with the below code. I must be missing something...

Database Class:
    class Database {
    private static $link = null;

    private static function dbLink() {
        if(self::$link) {
            return self::$link;
        }

        $dsn = null;

        switch(DB_DRVR) {
            case 'mysql':
                $dsn = DB_DRVR . ":host=" . DB_HOST . ";dbname=" . DB_NAME;
                break;
        }

        self::$link = new PDO($dsn, DB_USER, DB_PASS);

        return self::$link;
    }

    public static function fetchAssoc($sql) {
        $stmt = self::query($sql);
        $result = array();

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result;
    }

    public static function __callStatic($name, $arguments) {
        $callback = array(self::dbLink(), $name);
        return call_user_func_array($callback, $arguments);
    }
}

Portion of code returning error:
        $sql = "SELECT group FROM users WHERE username='ryan';";
        $dbSQL = Database::fetchAssoc($sql);

        echo $dbSQL['group'];

Database setup:
  • id(auto_increment, primary)
  • name(tinytext)
  • username(tinytext)
  • password(tinytext)
  • salt(tinytext)
  • email(tinytext)
  • group(tinytext)
  • privileges(tinytext)
I'm receiving the following error:
Fatal error: Call to a member function fetch() on a non-object
in C:\public_html\kernel\database.php on line 38

However the odd part is if I change the SQL to:
$sql = "SELECT * FROM users WHERE username='ryan';";

I don't get the error, it displays properly, and if I change the SQL statement to:
$sql = "SELECT username FROM users WHERE username='ryan';";

and call $dbSQL['username'] it works fine using the function above.
My Question: How come when I try to use the 'group' column in my $dbSQL array, I am receiving an error, but when I try to use the 'username' column, everything runs fine. What am I missing?
Thanks, Ryan

SELECT `group` FROM users WHERE username='ryan'

0 comments:

Post a Comment