I've been asked by my colleague to make a PHP function to plug into our web application to handle an infinite amount of nested (looped) queries to make our lives much easier, without being worried about loosing the current and/or previous results.
Here is the code I came up after minutes, and it seems that it works fine, however I still have these questions:
- Am I re-inventing the mysqli_prepare function?
- Is it smart to handling these nested queries in this way?
- What could be pros and cons of using the following approach?
The actual function:
function qn($query) {
global $db;
$rand_var = 'r' . mktime() . mt_rand();
$$rand_var = $db->query($query);
return $$rand_var;
}
and in action:
if (($db instanceof mysqli) != true) {
$db = new mysqli(DB_ADDRESS, DB_USER, DB_PASS, DB_NAME);
}
$a = qn('SELECT DISTINCT ***');
while ($row_a = $a->fetch_assoc()) {
// do some stuff
$b = qn('SELECT ***' . $row_a['foo']);
while ($row_b = $b->fetch_assoc()) {
$c = qn('SELECT COUNT(id)' . $row_b['bar']);
// keep going ...
}
}
Note: SQL queries are sample.
return $db->query($query);? Which to assign to local variable with unique name first?