简体   繁体   中英

Can fetch Data inside the class but when return it's send only boolean value php PDO?

I am trying to build database class using PDO this my first time using pdo so while i am building i am stuck in this problem i was able create and connect to database using class but problem is when i am trying to execute and fetch returned data error says

Call to a member function fetch() on boolean

and yet i can do this fetching inside the class this problem arise only when i am trying to fetch returned data and i have echoed the returned data it is returning 1

This is function that's trying to return (did not use parameters just using dummy)

 public function init($query,$param =[]){
        if(!$this->bConnected) { $this->Connect(); }
        try{
            $stmt = $this->pdo->prepare('SELECT * FROM business');
            $stmt->execute();
            return $stmt->execute();


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




     }

Calling to class object name is $myobj

 $stmt = $myobj->init('SELECT * FROM business',$value);

    while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){

        echo( $rows['bs_name'] ."  |" .$rows['bs_id']. "<br>");
    }

This is same code only difference is this is inside the class.working without any errors

   public function init($query,$param =[]){
        if(!$this->bConnected) { $this->Connect(); }
        try{
            $stmt = $this->pdo->prepare('SELECT * FROM business');
            $stmt->execute();
             $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
            while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
                echo( $rows['bs_name'] ."  |" .$rows['bs_id']. "<br>");
            }

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




     }

Your method returns the result of $stmt->execute() (a boolean indicating success/failure of the statement execution, not the query results ).

$stmt = $this->pdo->prepare('SELECT * FROM business');
return $stmt->execute();

Instead, for the method to work the way you're using it, you need to execute the statement and then return the statement itself, not the result of execute() .

$stmt = $this->pdo->prepare('SELECT * FROM business');
$stmt->execute();
return $stmt;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM