Error in PHP: "Fatal error: Call to a member function prepare ()"

0

When I try to run the SELECT on the server it accuses this msg: Fatal error: Call to a member function prepare() on a non-object in blog.php on line 97 the line referred to is this:

$readPost = $db->prepare($postagemRead);

A little more like this:

$pg = 1;
    $limite = 5;
    $inicio = ($pg * $limite) - $limite;

    $postagemRead = "SELECT * FROM postagem ORDER BY datapost DESC LIMIT :inicio,:limite";
    try{
            $readPost = $db->prepare($postagemRead);

the connection file is this:

<?php 
try{
        $db = new PDO("mysql:dbname=database;host=localhost;charset=utf8;","root","");
    }catch(PDOException $e){
        $e -> getMessage();
    }   
?>

I do not see the problem seen running this on the local server (wamp server) and running normal, but on the host of this error what can it be?

Error:

  

exception 'PDOException' with message 'SQLSTATE [28000] [1045] Access   denied for user 'root' @ 'localhost' (using password: NO) 'in   /home/vhosts/molbe.freetzi.com/config.php:3 Stack trace: # 0   /home/vhosts/molbe.freetzi.com/config.php(3):   PDO- > __ construct ('mysql: dbname = 85 ...', 'root', '') # 1   /home/vhosts/molbe.freetzi.com/padrao.php(1):   require_once ('/ home / vhosts / mo ...') # 2 {main} 'in   /home/vhosts/molbe.freetzi.com/config.php:5 Stack trace: # 0   /home/vhosts/molbe.freetzi.com/padrao.php(1): require_once () # 1 {main}   thrown in /home/vhosts/molbe.freetzi.com/config.php on line 5

    
asked by anonymous 10.07.2015 / 20:46

1 answer

1
  • The connection object was not saved in the $db variable. Therefore, the prepare function does not exist in $db . This is because ...

  • ... you are not exploding the error, that is, try {} catch() is not stopping your code and it is continuing, giving the illusion that $db exists. >

    Correct:

    try
    {
        $db = new PDO("mysql:dbname=database;host=localhost;charset=utf8;","root","");
    }
    catch(PDOException $e)
    {
        throw new PDOException($e);
    } 
    
  • After you've blown the error, you'll see which message on the connection failure in new PDO . If you do not see any more errors, the variable $db will exist correctly and therefore $db->prepare($postagemRead); will work .

    Tip

    Probably user root and password "" do not exist in host (remote server).

        
    10.07.2015 / 20:53