Adam Kolinski Adam Kolinski - 7 months ago 10
PHP Question

PDO - Listing blog entries with successful connection: Fatal error: Call to a member function prepare() on a non-object

I'm new to using PDO in PHP and using OOP. I've gone online to look at other stackoverflow questions for this error before posting. I have a feeling it might be with the code I have below thus why I am reaching out.

I'm trying to list the blog_titles for a table in my database.

<!DOCTYPE HTML>
<head>
<title>Simple blog</title>
</head>
<body>
<h1>Listing blog titles</h1>

<?php

include "system/connection.php";

$sql = "SELECT * FROM blogs ORDER BY id DESC";
$getentries = $dbh->prepare($sql);
if ($getentries->execute(array($_GET['blog_title']))) {
while ($row = $getentries->fetch()) {
print_r($row);
}
}

?>

</body>
</html>


The connection is successful. This is my connection script.

<?php

$servername = "localhost";
$dbname = "simple_blog";
$username = "root";
$password = "";

try {
global $dbh;
$dbh = new PDO('mysql:host=localhost;dbname=simple_blog', $username, $password);
{
print("Connection success!");
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>


This is the error I receive:


Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\simple-blog\index.php on line 13


Any guidance to helping me understand this would be greatly appreciated.

Thanks in advance.

Adam

Answer

It is simple, you are assigning null, after you are initiating a connection :)

    global $dbh;
    $dbh = new PDO('mysql:host=localhost;dbname=simple_blog', $username, $password);
    {
        print("Connection success!");
    }

remove the $dbh = null and you are good to go. Also, there is no need to assign it as global variable, since you are including it before you make a call to SQL.

I dont know why you assign null, but that means you are rewriting the connection with null.

If you have heard somewhere that "You need to close the connections", then that should be done after you have made the call to SQL and parsed the results, but in general in PHP there is no need to close connection, because it is taken care of.

Comments