phpsql-serverpdoextending-classes

prepare and execute in one method


I need PDO's prepare() and execute() in one method... but it doesn' work. Environment: IIS 10 / SQL Server 2014

class dbh extends PDO {
    ...
    public function xquery($sql){
        if(($sth = $this->prepare($sql)) === false){
            $error_arr = $this->errorInfo();
            $this->error .= '<span title="error_code:'.$error_arr[0].'">(prepare) '.$error_arr[1].':'.$error_arr[2].'</span>';
        }

        if($sth->execute() === false){
            $error_arr = $sth->errorInfo();
            $this->error .= '<span title="error_code:'.$error_arr[0].'">(execute) '.$error_arr[1].':'.$error_arr[2].'</span>';
        }
    }
}

Calling method

$sql = "SELECT * FROM table";
$dbh->xquery($sql) OR die($dbh->error);

Any suggestions appritiated!


Solution

  • Found the bug... xquery() should return $sth

    public function xquery($sql){
        if(($sth = $this->prepare($sql)) === false){
            $error_arr = $this->errorInfo();
            $this->error .= '<span title="error_code:'.$error_arr[0].'">(prepare) '.$error_arr[1].':'.$error_arr[2].'</span>';
        }
    
        if($sth->execute() === false){
            $error_arr = $sth->errorInfo();
            $this->error .= '<span title="error_code:'.$error_arr[0].'">(execute) '.$error_arr[1].':'.$error_arr[2].'</span>';
        }
    
        if(empty($this->error))
            return $sth;
    }