1

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!

1
  • try to do $result = $select->selecttema(); and in your sql connection code try to to do fetch stuff and return $row from there Commented Apr 22, 2015 at 22:24

1 Answer 1

1

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>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

@John Singer Might I just add that instancing PDO inside the class is the WRONG way to do this. Google for Dependency Injection to find out why and how you should be doing this instead
Thanks for the comment David Soussan! I investigate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.