Ryan
Ryan

Reputation: 59

PHP PDO Fetch_Assoc not returning 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

Upvotes: 3

Views: 1297

Answers (3)

Alan Pearce
Alan Pearce

Reputation: 1350

It sounds to me as if your query is failing because your RDBMS reserves the word group.

To avoid this type of problem in future:

Implement some error checking and you would see a clue from the DB server about which part of which query fails. There are a few ways you can do this:

  • Make sure your code checks self::errorInfo() after running each query, either printing or logging the output.
  • Switch your errormode to PDO::ERRMODE_EXCEPTION. See the manual page about Errors and error handling

Upvotes: 1

deceze
deceze

Reputation: 522510

GROUP is a reserved keyword in SQL, your query produces an error if you use it. Quote it:

SELECT `group` ...

Upvotes: 1

karka91
karka91

Reputation: 733

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

Upvotes: 4

Related Questions