Search code examples
phpmysqlwhile-loopstatic-variables

PHP: I can only use this function once (using it in a while loop)


I got an answer on an older question which is almost working.

I have a function,

function vraagOp($table,$where)
{
    static $rVraagOp;
    if(!$rVraagOp){
        $qVraagOp = "SELECT * FROM $table WHERE $where";
        $rVraagOp = mysql_query( $qVraagOp );
    }
    return mysql_fetch_assoc( $rVraagOp );
}

that I want to use like this

while (vraagOp("testtable","testtype = test")) 
{
   echo "testing <br>";
}

The function works fine, however, I can only use it one time per page. The second time I call it it doesn't do anything. No error either, it's just like the function never happend.

What do I have to change in order to make it work multiple times and still work in the while loop?


Solution

  • Use something like this:

    function vraagOp($table,$where)
    {
        static $rVraagOp = null;
        if(!isset($rVraagOp)){
            $qVraagOp = "SELECT * FROM $table WHERE $where";
            $rVraagOp = mysql_query( $qVraagOp );
        }
        $ret = mysql_fetch_assoc( $rVraagOp );
        if(!$ret) $rVraagOp = null;
        return $ret;
    }
    

    It's ugly, but if you want like that...