How do I resolve the prepare error for this script?

Asked

Viewed 53 times

1

I’ve been looking for a solution for 2 hours [this problem][1]. I am starting a course of Virtual store with PHP and the mistake is this: he says I’m trying to give a prepare in an unincorporated object.

The logic is this: he made the class of CRUD and is installing it for the time being, just to illustrate, inside the class file Conndb. Why is this error occurring?

Dei highlight_file in the files so they can see the script and the error.

// autoload - para chamar todas as classes instanciadas
function __autoload($class) { require_once "{$class}.class.php"; }

// final - pode instanciar mas não pode extender
// abstract - pode extender mas não pode instanciar 
abstract class ConnDB
{
    private static $conexao;

    private function setConn()
    {
        is_null(self::$conexao) ? 
                self::$conexao = new PDO("mysql:host=mysql.axitech.com.br;dbname=dbname", "user", "pass") :
                self::$conexao;
    }

    public function getConn()
    {
        return $this->setConn();
    }
}

$inserir = new CRUD;
$inserir->insert('user', 'user=?, email=?, cidade=?', array('yesmarcos', '[email protected]', 'Campo Grande'));

Fatal error: Call to a Member Function prepare() on a non-object in /home/axitech/www/mylojavirtual/require/class/CRUD.class.php on line 11

  • 1

    It seems that your connection is not being returned in setConn() of the one return self::$conexao should already correct the first mistake.

  • 1

    xD the question user and password, if not the galley will access

  • 1

    In the other file do include ConnDB

  • Thanks @rray really missed the Return in the is_null

  • 1

    @Marcosvinicius If possible, answer your own question here and mark as accepted, so that others can more easily find the solution to similar problems.

1 answer

1

Well folks, the only problem in that case there is that I was forgetting to return the result of the setConn and the getConn in turn was returning nothingness since the method setConn also was not returning anything. It was like this:

// autoload - para chamar todas as classes instanciadas
function __autoload($class) { require_once "{$class}.class.php"; }

// final - pode instanciar mas não pode extender
// abstract - pode extender mas não pode instanciar 
abstract class ConnDB
{
    private static $conexao;

    private function setConn()
    {
         return  // <----- O erro era aqui          
         is_null(self::$conexao) ? 
                self::$conexao = new PDO("mysql:host=mysql.axitech.com.br;dbname=dbname", "user", "pass") :
                self::$conexao;
    }

    public function getConn()
    {
        return $this->setConn();
    }
}

$inserir = new CRUD;
$inserir->insert('user', 'user=?, email=?, cidade=?', array('yesmarcos', '[email protected]', 'Campo Grande'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.