looping over a recordset

looping over a recordset

by Martin H -
Number of replies: 7

Hi all,

Does anyone know if it is possible to loop over a record set (output of $DB->get_recordset_sql()) more than just one time?

I have 2 foreachs. the first one works but the second one doesn't work. I mean execution doesn't fo inside of it.

code is simply like this:

foreach ($rs as $record) {
// ...
}
if ($failed) { foreach
($rs as $record) { // ... } }

Thanks

Average of ratings: -
In reply to Martin H

Re: looping over a recordset

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

If you need to go through the data more than once, why not use 'get_records_sql' instead of 'get_recordset_sql'?


In reply to Davo Smith

Re: looping over a recordset

by Martin H -

because get_records causes memory over usage and my server returns error.

In reply to Martin H

Re: looping over a recordset

by Darko Miletić -

Of course you can repeat the process if needed. Just do this before doing the loop:

$rs->rewind();


In reply to Darko Miletić

Re: looping over a recordset

by Martin H -

Thanks Darko

However, rewind is not implemented yet.

/**
* Rewinds are not supported!
* @return void
*/
public function rewind() {
// no seeking, sorry - let's ignore it ;-)
return;
}

In reply to Martin H

Re: looping over a recordset

by Darko Miletić -

You are indeed right. In that case you can either reissue get_recordset again or rethink your query to fetch less records using get_records where you can loop as many times you like.

In reply to Martin H

Re: looping over a recordset

by Darko Miletić -

You can also try this if you really need rewind and use MySQL:


class myrecordset extends mysqli_native_moodle_recordset {

    public function __construct(mysqli_native_moodle_recordset $rs) {
        $this->result = $rs->result;
    }

    public function __destruct() {
        $this->result = null;
        $this->current = null;
    }

    public function rewind() {
        $this->result->data_seek(0);
        $this->current = $this->next();
    }

}

$recordset = $DB->get_recordset('user');
$myrec = new myrecordset($recordset);

// rewind is called every time foreach is initiated
foreach ($myrec as $record) {
    // first pass
}

foreach ($myrec as $record) {
    // second pass
}

foreach ($myrec as $record) {
    // third pass
}

In reply to Darko Miletić

Re: looping over a recordset

by Darko Miletić -

Nvm, I just reviewed the record code again and noticed that all recordsets CLOSE their resultset after you reach the end so rewinding is not possible.