PHP PDO Noob Question

Can someone help me i think i miss something from OOP theory

The question is why why i have to assign $dbh->query($sql) into $STH in order to use $STH->fetch();

Moreover can you please guide on what to read in order to understand more?


    $dbName = 'db';
    $dbConn = 'localhost';
    $dbUser = 'root';
    $dbPass = '';
    $dbh= new PDO($dsn, $dbUser,  $dbPass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
     catch (PDOException $e){
    echo 'error' .$e->getMessage();
    $sql = "select question from tbl_choice ";
    //why i have to assign $dbh->query($sql) into $STH in order to use $STH->fetch();
    $STH = $dbh->query($sql);
    while ($row = $STH->fetch()) {
        echo $row['question'];

Open in new window

Who is Participating?
Dave BaldwinConnect With a Mentor Fixer of ProblemsCommented:
It's not just an identifier but also an object of a class that contains both the result that is returned and the methods to operate on them.  If you read the PDO pages I linked, you'll see that there is more than one way to get to the result set returned by the query.
Dave BaldwinFixer of ProblemsCommented:
This is the PDO home page on  In $STH = $dbh->query($sql); , $dbh is the PDO connection, $sql is the query, and $STH is your result set.  You need $STH to tell fetch() which result set to work with.  It's an identifier and there can be more than one result set on a page.
MiltonAuthor Commented:
Yes i understood that $dbh is PDO connection and $sql is the query and i now i understand that $STH is an identifier so basically $STH becomes $dbh->query($sql)
but how  $STH can do $STH-> it becomes object?
or should i say how $dbh->query($sql) can do $dbh->query($sql)->fetch(); ?

i tried var_dump($STH) and it returned
public 'queryString' => string ''select question from tbl_choice' (length=31)

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.