Link to home
Start Free TrialLog in
Avatar of Milton
MiltonFlag for Greece

asked on

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?

Thanks

    $dbName = 'db';
    $dbConn = 'localhost';
    $dbUser = 'root';
    $dbPass = '';
    $dsn="mysql:host=$dbConn;dbname=$dbName;";
    try{
    $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);
       
    $STH->setFetchMode(PDO::FETCH_ASSOC);
     
    while ($row = $STH->fetch()) {
     
        echo $row['question'];
       
        }

Open in new window

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

This is the PDO home page on PHP.net: http://us3.php.net/manual/en/book.pdo.php  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.
Avatar of Milton

ASKER

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
object(PDOStatement)[2]
public 'queryString' => string ''select question from tbl_choice' (length=31)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial