mauzilla
mauzilla

Reputation: 3592

Returning a single value using PDO MYSQL

I am crossing over to PDO and want to, simply put, return a single value from a table (and I feel really stupid for not getting it right). I am not getting any errors, but also no values, where there should be :)

 try {
        $sql = "SELECT `column_name` FROM `table` ORDER BY `id` DESC LIMIT 1";
        $query = $this->handler->query($sql);
        $result = $query->fetchColumn();
        print_r($result);
    } 
    catch(PDOException $e) {
        return false;
    }
    return true;

Upvotes: 1

Views: 358

Answers (1)

Makita
Makita

Reputation: 1812

Print the error message:

catch(PDOException $e) {
    print_r($e->getMessage());
    return false;
}

As shown this would work, if you have correctly connected to the database. Check that your object is successfully connecting to the database, and that you have the correct column name and table name.

A snippet from one of my DB classes:

/**********************************************************************
*  Try to connect to mySQL database
*/
public function connect($dbuser, $dbpassword, $dbhost ,$dbname)
{
    try {
        $this->dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return true;
    } catch (PDOException $e) {
        $this->setError($e->getMessage());
    }
}

Upvotes: 5

Related Questions