Scarface
Scarface

Reputation: 3913

How to include file multiple times in PHP?

I have a standardized sequence of code which I used to display topic information on the home page and other pages on my site. I want to throw it in an include file so that I don't have to keep fixing multiple pages. The problem is sometimes this include occurs in a while statement which means there was a previous query supplying information for sorting purposes.

When the code is raw in the while statement, it works as it should and if there are multiple ids being served to the code from the previous query, it shows multiple results. However, if this code is in an include, I will only see one result. I assume because the include file only executes once. How would I serve an include file as the equivalent as my raw code?

Include

//outside query
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $topic_id=htmlspecialchars( $row['topic_id'], ENT_NOQUOTES, 'UTF-8' );
    //code to display topics
    include('display_topics.php');  
}

Raw Code

//outside query
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    //code to display topics
    $sql = "SELECT * FROM topic WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1,topic_id, PDO::PARAM_INT);
    $result=$stmt->execute();
}

while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    //yada yada
    ...
}

Upvotes: 1

Views: 2252

Answers (3)

cwallenpoole
cwallenpoole

Reputation: 82028

That word, I don't think it is for what you think it is for.

Generally, include's use should not be used that way. That's why God invented functions (or Ada Byron, if you're not theologically inclined).

Try this instead:

function execute_row($row, $conn)
{
    $topic_id=htmlspecialchars( $row['topic_id'], ENT_NOQUOTES, 'UTF-8' );
    $sql = "SELECT * FROM topic WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1,topic_id, PDO::PARAM_INT);
    return $stmt->execute();
}

Then, in your while statement:

while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $result = execute_row($row, $conn);
}

TADA! And the best part is, it makes your code smaller, easier to read, and faster to parse.

Upvotes: 1

Peetz
Peetz

Reputation: 167

Include the file as normal, but put the repeated code in a function. Then, where you wish to add the code simply call the function.

Upvotes: 1

Pekka
Pekka

Reputation: 449465

Don't do it this way.

It's much better to do one include, and to declare a function in it that does what you need:

function display_topics($topic_id)
 { 
   ....
 }

Call that function inside the loop, and pass all necessary data to it.

Upvotes: 12

Related Questions