I am trying to store an array of fetched data into a session, with the code below, but when i try to execute it, the execution time exceeds 30 seconds and it fails. I can't seem to spot the error, so i'm hoping for a helping hand.
public function stat_query($user_id = null)
{
$query = $this->core->conn->query("SELECT user_stats.value as value, stats.shortname as shortname FROM user_stats INNER JOIN stats ON user_stats.stat_id = stats.id WHERE user_stats.user_id = ".$this->get_user($user_id));
$value = $query->fetch(PDO::FETCH_ASSOC);
return $value;
}
public function init_stat_array($user_id = null){
while($query = $this->stat_query($this->get_user($user_id))) {
$this->temp_array[$query['shortname']] = $query['value'];
}
}
public function store_session($user_id = null) {
$this->init_stat_array($this->get_user($user_id));
$_SESSION['stats'] = $this->temp_array;
}
Note: the the get_user function works as intended, it just returns the user that was bound in the constructor, or the inputted user.
The while loop does not work this way. Using while on fetch_assoc
like while ($row = $this->core->conn->fetch()
works because the fetch
method is intended to work this way. Once you assign the return value of the fetch method to a variable (or method return value), runing while()
on it won't work as running while()
on fetch method, but as running while()
on your method. So while($this->yourMethod($value))
is always true if the method return non-false value when passing $value to it.
If a method return an array, then while is an overkill, because you will need to use key()
and some other function to interact with arrays. In you case you need foreach()
:
public function init_stat_array($user_id = null){
foreach($this->stat_query($this->get_user($user_id)) as $row) {
$this->temp_array[$row['shortname']] = $row['value'];
}
}
stat_query
starts the query and fetches the first row. It will run indefinitely because it should return a truthy result with the $this->get_user($user_id)
argument, and that argument does not change. The simplest way to fix this would be to just remove the while
, since that query should only return a single row anyway (I assume that the user_id is canonical).
You could also return the result set ($query
) from that method and iterate over it in another method. You would just have to call fetch
externally.
I think that what you may want to loop over is init_stat_array
since it would make sense to run stat_query
for an array of user_ids.