If I try to run the following PHP code, I get a "Call to a member function query() on a non-object". Do you know why? I use the same code on another site (http://daveismyname.com/creating-a-blog-from-scratch-with-php-bp#.U6fdxPmSxmx), where it works just fine.

config.php

<?php
ob_start();
session_start();

//database credentials
$username = "demo"; 
$password = "demo"; 
$host = "localhost"; 
$dbname = "try";  

try{
$db = new PDO('mysql:host=localhost;dbname=try', $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    echo "I'm sorry, I'm afraid i cant do that.";
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    $db = null;
}


//set timezone
date_default_timezone_set('Europe/London');

//load classes as needed
function __autoload($class) {

   $class = strtolower($class);

   //if call from within assets adjust the path
   $classpath = 'classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
   }  

   //if call from within admin adjust the path
   $classpath = '../classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
   }

   //if call from within admin adjust the path
   $classpath = '../../classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
   }     

}

$user = new User($db); 

include('functions.php');
?>

index.php

   <?php require('includes/config.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Blog</title>
    <link rel="stylesheet" href="style/normalize.css">
    <link rel="stylesheet" href="style/main.css">
</head>
<body>

    <div id="wrapper">


        <h1>Blog</h1>
        <hr />

        <div id='main'>

            <?php
                try {

                    $pages = new Paginator('1','p');

                    $stmt = $db->query('SELECT postID FROM blog_posts_seo');

                    //pass number of records to
                    $pages->set_total($stmt->rowCount());

                    $stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo ORDER BY postID DESC '.$pages->get_limit());
                    while($row = $stmt->fetch()){

                            echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
                            echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';

                                $stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
                                $stmt2->execute(array(':postID' => $row['postID']));

                                $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);

                                $links = array();
                                foreach ($catRow as $cat)
                                {
                                    $links[] = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
                                }
                                echo implode(", ", $links);

                            echo '</p>';
                            echo '<p>'.$row['postDesc'].'</p>';               
                            echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';
                    }

                    echo $pages->page_links();

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

        </div>

        <div id='sidebar'>
            <?php require('sidebar.php'); ?>
        </div>

        <div id='clear'></div>

    </div>


</body>
</html>

Hi, check line 12 in your config file: the host and dbname values are hardcoded, change the line with:

$db = new PDO("mysql:host={$host};dbname={$dbname}", $username, $password);

hi, thank for help but i still get this (call to a member function query() on a non-object)

Ok, then check the contents of the file PDOErrors.txt, you should be able to read the reason why the connection to the database is failing.

Did you setup the DB?

PDOErrors.txt :- SQLSTATE[HY000] [1045] Access denied for user 'demo'@'localhost' (using password: YES).. what should I do?

DB? I already set up the DB

what should I do?

Use the correct credentials (user and password) to access the database, so change these values in your config file:

$username = "demo"; 
$password = "demo"; 
$host = "localhost"; 
$dbname = "try";

Check always the last line of the error log, since the information is appended to the bottom of the file. To increase the readability of the error log, I suggest you to change line 17 of your config file with this:

$error_message = date('Y-m-d G:i:s') . " [ERROR]: " . $e->getMessage() . "\n\r";
file_put_contents('PDOErrors.txt', $error_message, FILE_APPEND);

It should output a bit better, separating each error by a carriage return.

From this code

    try{
    $db = new PDO('mysql:host=localhost;dbname=try', $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        echo "I'm sorry, I'm afraid i cant do that.";
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        $db = null;
    }

to

    try{
    $db = new PDO('mysql:host=localhost;dbname=try', $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        echo
       $error_message = date('Y-m-d G:i:s') . " [ERROR]: " . $e->getMessage() . "\n\r";
       file_put_contents('PDOErrors.txt', $error_message, FILE_APPEND);
        $db = null;
    }

when I try to run this code, I get this

Fatal error: Call to a member function query() on a non-object in index.php on line 25

and also I get this

PDOErrors.txt :-SQLSTATE[HY000] [1045] Access denied for user 'demo'@'localhost' (using password: YES)

am I wrong?

The error:

Fatal error: Call to a member function query() on a non-object in index.php on line 25

Is a consequence of:

SQLSTATE[HY000] [1045] Access denied for user 'demo'@'localhost' (using password: YES)

And as in my previous post:

Use the correct credentials (user and password) to access the database...

Which means that username or password for your database are wrong. Does user demo exists in your database? It has privileges to access the database named try?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.