John Siniger
John Siniger

Reputation: 885

Fetch Array from class with PDO

Hello I would like to see if someone can help me with the following. I am selecting some results from database with PDO, which SQL query is inside a class file inside /class/functions.php. The problem is that I can't make it display the results in php file inside a form.

Here is the SQL query which I am using inside class/functions.php:

class Users {    
public function selecttema() {
        try{
                $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
                $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                $sql = "SELECT * FROM topics";

                $stmt = $con->prepare( $sql );

                $stmt->setFetchMode(PDO::FETCH_ASSOC);
                $stmt->execute();               

             }catch (PDOException $e) {
                 echo $e->getMessage();
                 }

    }}

After that on the external file I am trying to display the information from this query with the following code:

<?php 
            $select = new Users;
            $select->selecttema();
            while( $row = $stmt->fetch()){ 
            echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
            } ?>

I am getting the following errors:

Notice: Undefined variable: stmt in E:\xampp\htdocs\doccms\add_doc.php on line 83

Fatal error: Call to a member function fetch() on null in E:\xampp\htdocs\doccms\add_doc.php on line 83

Any help will be welcome. thanks!

Upvotes: 1

Views: 122

Answers (1)

Barmar
Barmar

Reputation: 780974

The variable $stmt is local to the function. You need to return the value:

public function selecttema() {
    try{
        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "SELECT * FROM topics";

        $stmt = $con->prepare( $sql );

        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $stmt->execute();               
        return $stmt;
    }catch (PDOException $e) {
        echo $e->getMessage();
        return false;
    }

}

Then use that in the caller:

$statement = $select->selecttema();
while ($row = $statement->fetch()) {
    echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}

Upvotes: 1

Related Questions