tags:

views:

42

answers:

1

I have a large PHP loop that I'm re-using in multiple spots on multiple pages of my site. I'd normally just use an include() to set that PHP loop wherever it's needed, but the PHP loop in question makes use of a MySQL query in which I need to change variables (different filters and different LIMITs) for different instances of this PHP loop.

<?php 
    $results = mysql_query("SELECT * FROM databaseName ORDER BY columnName DESC, otherColumnName DESC LIMIT 6", $connection);
    if (!$results) {
        die("Database Query Failed");
    }
?>

<?php
    while ($variable = mysql_fetch_array($results)) {
        ----Execute this loop----
    };
?>

Which I then recalled wherever I needed it using

<?php include("/filepath/includedfile.php"); ?>

Everything was running fine until I took the actual MySQL query OUT of the included file and placed it before each instance of that included PHP (so I could control certain variables for each instance of the query). Now, the MySQL query and the included PHP loop don't seem to be communicating the same way, and I'm getting the following warning:

"Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/filepathhere/includedfile.php on line 3"<

I feel like the included PHP is being run in the included file and THEN being injected into the main page. I need the code to be injected into the main page before it gets run.

Is there a better way than "include()" to inject that PHP loop into the main page?

+3  A: 

Seems like a good time to learn about functions and function arguments. :)


To elaborate: including a file is one way to reuse code, but as you are experiencing, there's no controlled way of altering that code's behavior. A function has a clearly defined interface to pass arguments into the function, which you can use inside the function to alter its behavior.

function my_big_loop($condition) {

    // preparations

    $condition = mysql_real_escape_string($condition);  // always! even for simple examples. :)
    $results = mysql_query("SELECT * FROM somewhere WHERE x = '$condition'");

    // do loopy stuff

    return $big_pile_of_HTML;
}

echo my_big_loop('somecondition');
deceze
Thanks for the links... these were very helpful
Distill