1

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->prepare("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.

1 Answer 1

1

inclusion of files is wrong;

include index.php on function.php page only , dont include vice versa

best practice to use include_once

Sign up to request clarification or add additional context in comments.

2 Comments

If I do that I have the files including each other, and they just keep loading.
I need index.php to load functions.php, index.php is a dynamic template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.