Fatal error: Call to a member function prepare() on a non-object with PDO
I have a file that includes another file:
index.php is a dynamic template
<?php
$db = new PDO("mysql:host=localhost;dbname=db", $DB_USER, $DB_PASSWORD);
include(functions.php);
?>
functions.php
<?php
$preparedStatement = $db->prepare("SELECT id FROM table LIMIT 1");
$preparedStatement->execute();
$firstId = $preparedStatement->fetchAll();
?>
when functions.php executes I get:
Fatal error: Call to a member function prepare() on a non-object
at line
$preparedStatement = $db->pre开发者_JAVA技巧pare("SELECT id FROM table LIMIT 1");
What is wrong with this code such that it throws the error?
Edit: The error arose from me connecting directly the the functions.php file, it did not appear when it was included from index.php, the problem I had was content not loading in later inclusions, that was caused by me forgetting to properly address arrays in a later included file. The selected answer is correct for the question I presented.
inclusion of files is wrong;
include index.php
on function.php
page only , dont include vice versa
best practice to use include_once
精彩评论