Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic Variables in Function after while loop
    primarykey
    data
    text
    <p>I have a database abstraction layer in a CMS, and one of the functions is a mysql_fetch_assoc wrapper which includes the connection, query and result logic all in one.</p> <pre><code>_select_row($in_table, $in_what = '*', $in_where = '', $in_arr_params = array(), $in_flags) { // Generates a unique enough name based on query contents. $hash = md5($in_table.$in_what.implode((array)$in_arr_params).$in_flags); if (!isset($_STATIC)) { static $_STATIC = array(); } if (isset($_STATIC[$hash]) { return mysql_fetch_assoc($_STATIC[$hash]); } // *snip* SQL logic here, connect -&gt; query -&gt; result *snip* $_STATIC[$hash] = $result; return mysql_fetch_assoc($_STATIC[$hash]); } </code></pre> <p>It maintains a static variable so when being used in loops, it can iterate like a standard fetch_assoc call.</p> <pre><code>while (_select_row('mytable')) // Loops all rows { // Do Stuff } </code></pre> <p>The only problem I'm having is a corner case: if the programmer tries to make the same query again later in the script, it will continue the iteration instead of starting again. I could create a reset function of some sort, or work with a selector function and a results function, but I was hoping for a more elegant solution in which the function would "know" when it was not being called in the same loop, and dump the results. Also, just for efficiency sake I'd like it to dump results when they are done.</p> <p>Any ideas, or is switching to a select->result model really the only way around this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload