Tom Bird
Tom Bird

Reputation: 1039

PDO Error - Call to a member function prepare() on a non-object

I'm having an issue with a class I created that uploads a file. This class has a parent class which is the database access layer. The uploads looks like this:

<?php

class upload extends bao {

    // general variables
    private $basePath = '../../uploads/';
    private $fullMaxWidth = 1000;
    private $mediumMaxWidth = 500;
    private $smallMaxWidth = 250;
    private $errors = 0;
    private $difference = 0;
    private $debugging = false;

    private $maxFileSize = 100000000;

    // current file variables
    private $currFileName = '';
    private $currFileType = '';
    private $currFileTmpName = '';
    private $currFileError = 0;
    private $currFileSize = 0;
    private $currExt = '';

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        This will overwrite any default values with whats supplied

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    public function __construct( $params = null ) {

        if($this -> debugging) {
            echo '__construct method';
        }

        if( $params ) {
            foreach( $params as $key => $val ) {
                $this -> $key = $val;
            }
        }

        $this -> initiate();
    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Initiates the upload process

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    private function initiate() {

        if( $this -> debugging ) {
            echo 'initiate method';
        }

        for($i = 0; $i < count($_FILES['files']['name']); $i++) {
            $fileCheck = $this -> checkFileSize( $_FILES['files']['size'][$i] );
            if(!$fileCheck) {
                $this -> errors++;
            }

            $this -> currFileType = $_FILES['files']['type'][$i];
            $this -> currFileTmpName = $_FILES['files']['tmp_name'][$i];
            $fileExtPath = pathinfo($_FILES['files']['name'][$i]);
            $this -> currExt = strtolower($fileExtPath['extension']);

            if($this -> errors < 1) {
                $this -> switcher();
            }

        }

    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Runs a check to see what the file size is

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    private function checkFileSize( $fileSize ) {

        if($this -> debugging) {
            echo 'checkFileSize method';
        }

        if($fileSize <= $this -> maxFileSize) {
            return true;
        } else {
            return false;
        }

    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Determines which type of file it is

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    private function switcher() {

        if($this -> debugging) {
            echo 'switcher method';
        }

        if( $this -> currFileType == 'image/gif' || $this -> currFileType == 'image/png' || $this -> currFileType == 'image/jpeg') {
            $this -> image();
        } else {
            $this -> other();
        }
    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Uploads all image files

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    private function image() {

        if($this -> debugging) {
            echo 'image method';
        }

        $rand = rand(1000, 10000);
        $newFullName = time() .'-'. $_COOKIE['isLogged'] .'-'. $rand .'-full.'. $this -> currExt;
        $newMediumName = time() .'-'. $_COOKIE['isLogged'] .'-'. $rand .'-medium.'. $this -> currExt;
        $newSmallName = time() .'-'. $_COOKIE['isLogged'] .'-'. $rand .'-small.'. $this -> currExt;
        $fullPath = $this -> basePath . $newFileName;   

        $info = getimagesize( $this -> currFileTmpName );

        $fullWidth = $this -> getNewWidth( $this -> fullMaxWidth, $info[0] );
        $mediumWidth = $this -> getNewWidth( $this -> mediumMaxWidth, $info[0] );
        $smallWidth = $this -> getNewWidth( $this -> smallMaxWidth, $info[0] );

        $fullDif = $this -> setDifference( $this -> fullMaxWidth, $info[0] );
        $mediumDif = $this -> setDifference( $this -> mediumMaxWidth, $info[0] );
        $smallDif = $this -> setDifference( $this -> smallMaxWidth, $info[0] );

        $fullHeight = $this -> getNewHeight( $info[1], $fullDif );
        $mediumHeight = $this -> getNewHeight( $info[1], $mediumDif );
        $smallHeight = $this -> getNewHeight( $info[1], $smallDif );


        // set debugging to try to output new image sizes
        if( $this -> debugging ) {
            echo $fullWidth .' - '. $fullHeight .'<br/>';
            echo $mediumWidth .' - '. $mediumHeight .'<br/>';
            echo $smallWidth .' - '. $smallHeight .'<br/>';
        }

        $smallImage = imagecreatetruecolor($smallWidth, $smallHeight);
        $mediumImage = imagecreatetruecolor($mediumWidth, $mediumHeight);
        $fullImage = imagecreatetruecolor($fullWidth, $fullHeight);


        switch($info['mime']) {
            case 'image/gif':
                $smallImg = imagecreatefromgif( $this -> currFileTmpName );
                $mediumImg = imagecreatefromgif( $this -> currFileTmpName );
                $fullImg = imagecreatefromgif( $this -> currFileTmpName );
            break;

            case 'image/png':
                $smallImg = imagecreatefrompng( $this -> currFileTmpName );
                $mediumImg = imagecreatefrompng( $this -> currFileTmpName );
                $fullImg = imagecreatefrompng( $this -> currFileTmpName );
            break;

            default:
                $smallImg = imagecreatefromjpeg( $this -> currFileTmpName );
                $mediumImg = imagecreatefromjpeg( $this -> currFileTmpName );
                $fullImg = imagecreatefromjpeg( $this -> currFileTmpName );
            break;
        }

        imagecopyresampled($smallImage, $smallImg, 0, 0, 0, 0, $smallWidth, $smallHeight, $info[0], $info[1] );
        imagecopyresampled($mediumImage, $mediumImg, 0, 0, 0, 0, $mediumWidth, $mediumHeight, $info[0], $info[1] );
        imagecopyresampled($fullImage, $fullImg, 0, 0, 0, 0, $fullWidth, $fullHeight, $info[0], $info[1] );


         if($info['mime'] == 'image/gif') {
              imagegif( $smallImage, $this -> basePath . $newSmallName );
              imagegif( $mediumImage, $this -> basePath . $newMediumName );
              imagegif( $fullImage, $this -> basePath . $newFullName );
         } elseif($info['mime'] == 'image/png') {
              imagepng( $smallImage, $this -> basePath . $newSmallName, 8);
              imagepng( $mediumImage, $this -> basePath . $newMediumName, 8);
              imagepng( $fullImage, $this -> basePath . $newFullName, 8);
         } else {
              imagejpeg( $smallImage, $this -> basePath . $newSmallName, 80);
              imagejpeg( $mediumImage, $this -> basePath . $newMediumName, 80);
              imagejpeg( $fullImage, $this -> basePath . $newFullName, 80);
         }

        // insert into database
        $stringQuery = "INSERT INTO uploads (uid,smallFilename,mediumFilename,fullFilename,typeFile,status,createdOn,modifiedOn)VALUES(:uid, :smallFilename, :mediumFilename, :fullFilename, :typeFile, :status, :createdOn, :modifiedOn )";
        $binding = array(":uid" => $_COOKIE['userId'], ":smallFilename" => $newSmallName, ":mediumFilename" => $newMediumName, ":fullFilename" => $newFullName, ":typeFile" => $this -> currExt, ":status" => "new", ":createdOn" => currentTime, ":modifiedOn" => currentTime );

        $insertDB = parent::query( $stringQuery, $binding );

         if( !$insertDB ) {
            $this -> errors++;
         }
    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Uploads all files minus images

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    private function other() {

        if($this -> debugging) {
            echo 'other method';
        }

        $rand = rand(1000, 10000);
        $newFullName = time() .'-'. $_COOKIE['isLogged'] .'-'. $rand .'.'. $this -> currExt;
        $fullPath = $this -> basePath . $newFullName;

        if(move_uploaded_file($this -> currFileTmpName, $fullPath)){

            $stringQuery = "INSERT INTO uploads (uid,fullFilename,title,description,keywords,typeFile,uploadedType,uploadedId,status,createdOn,modifiedOn)VALUES(:uid,:fullFilename,:typeFile,:uploadedType,:uploadedId,:status,:createdOn,:modifiedOn)";
            $binding = array( ":uid" => $_COOKIE['userId'], ":fullFilename" => $newFullName, ":typeFile" => $this -> currExt, ":uploadedType" => "", ":uploadedId" => "", ":status" => "new", ":createdOn" => currentTime, ":modifiedOn" => currentTime );

            $insertDB = parent::query( $stringQuery, $binding );

            if( !$insertDB ) {
                $this -> errors++;
            }

        } else {
            echo 'There was an error';
        }
    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        Utility methods

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

    // if image does not match size set the difference
    private function setDifference( $fullwidth, $width ) {

        if($this -> debugging) {
            echo 'setDifference method';
        }

        return $fullwidth / $width;
    }

    // calculate the new width
    private function getNewWidth( $fullwidth, $width ) {

        if($this -> debugging) {
            echo 'getNewWidth method';
        }

        $this -> difference = $fullwidth / $width;
        return round($width * $this -> difference);
    }

    // calculate the new height
    private function getNewHeight( $height, $diff ) {

        if($this -> debugging) {
            echo 'getNewHeight method';
        }

        $newHeight = round($height * $diff );
        return $newHeight;
    }

    // creates new image for 3 sizes
    private function createImageTrueFull( $width, $height ) {

        if($this -> debugging) {
            echo 'createImageTrueFull method';
        }

        return imagecreatetruecolor( $width, $height );
    }
}

?>

The base database access layer looks like this:

<?php

class bao {

    private $environments = array(

        'development' => array(

        ),

        'test' => array(

        ), 

        'review' => array(

        ), 

        'production' => array(

        ), 

    );

    private     $url        = '',
                $host       = '',
                $dbname     = '',
                $user       = '',
                $pass       = '';

    /*
        Variable for connection
    */
    private     $connection;

    /*
        Init method
    */
    public function __construct( $params = null ) {

        $this -> setConnectionData();
        $this -> overwriteSettings( $params );
        $connection = $this -> connect();

    }

    public function setConnectionData() {

        if( strpos( $_SERVER['HTTP_HOST'], 'dev' ) ) {
            $envVariable = 'development';
        } elseif( strpos( $_SERVER['HTTP_HOST'], 'test' ) ) {
            $envVariable = 'test';
        } elseif( strpos( $_SERVER['HTTP_HOST'], 'review' ) ) {
            $envVariable = 'review';
        } else {
            $envVariable = 'production';
        }

        $this -> url = $this -> environments[$envVariable]['url'];
        $this -> host = $this -> environments[$envVariable]['host'];
        $this -> dbname = $this -> environments[$envVariable]['dbname'];
        $this -> user = $this -> environments[$envVariable]['user'];
        $this -> pass = $this -> environments[$envVariable]['pass'];
    }

    /*
        Overwrite any required values from default
    */
    private function overwriteSettings( $params ) {
        if( $params ) {
            foreach( $params as $key => $val ) {
                $this -> $key = $val;
            }
        }
    }

    /*
        Connect to database and then assign to variable
    */
    private function connect() {
        $this -> connection = new PDO( sprintf( 'mysql:host=%s;dbname=%s', $this -> host, $this -> dbname ), $this -> user, $this -> pass );
    }

    public function openQuery( $query, $params = null ) {

        if( $params ) {
            return $this -> query( $query, $params );
        } else {
            return $this -> query( $query );
        }
    }

    public function openFetchall( $sth ) {
        return $this -> fetchAll( $sth );
    }

    /*
        Runs actual query
    */
    protected function query( $query, $params = null ) {

        $sth = $this -> connection -> prepare( $query );

        if( $params ) {
            $sth -> execute( $params );
        } else {
            $sth -> execute();
        }

        return $sth;
    }

    public function openNumRows( $sth ) {
        return $this -> numRows( $sth );
    }

    protected function numRows( $sth ) {
        return $sth -> rowCount();
    }

    public function openFetch( $sth ) {
        return $this -> fetch( $sth );
    }

    protected function fetch( $sth ) {
        return $sth -> fetch( PDO::FETCH_ASSOC );
    }

    protected function fetchAll( $sth ) {
        return $sth -> fetchAll( PDO::FETCH_ASSOC );
    }

    protected function lastId( $sth ) {
        return $this -> connection -> lastInsertId();
    }

}

?>

Now when I run the script I get this error:

Fatal error: Call to a member function prepare() on a non-object in /home/content/51/8932751/html/sites/clients/OwnerBusinessLoans/www/dev/lib/helpers/bao.php on line 118

Which I don't understand why because I am simply running prepared query from my upload class the same way I have for all my other querys and they ran completely fine and did not show this error. In regards to syntax and the way I am doing things, this is the way I do it for over 10 other classes and I never receive any errors.

In my bao class I did remove the connections details but they are there where I am testing the app.

At first I thought it was query syntax or something so I changed and checked and rechecked all my syntax and that looks fine. If it's that my PDO instance is undefined I don't understand why because its defined the same way and used the same throughout all my other classes.

Any help would be greatly appreciated, I've been racking my brain on this and I feel like it has to be something small!

Thanks

Upvotes: 0

Views: 133

Answers (1)

Phil
Phil

Reputation: 164826

Your extending class needs to call the parent constructor in order to perform the bao construction sequence which includes creating the database connection. For example...

class upload extends bao {
    // snip

    public function __construct($params = null) {
        parent::__construct($params);

        // now the rest of the upload class code

See http://php.net/manual/language.oop5.decon.php, specifically

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Upvotes: 3

Related Questions