I am new to the php fat-free framework, and I am trying figure out how to loop through my mysql query results, or better yet, get it as an associative array (for learning purposes only).
What I did so far is
while(!$users->dry()){
array_push($user_assoc,$users->cast());
$users->next();
}
This works, but I was wondering if there is a better way of doing this? Also how do I setup a error handler? I mean how do I check if the query had any errors (i.e. fat-free equivalent of mysql_error()
)?
You're already using the correct way. At least if you want to use the mapper. By using the SQL class directly, an associative array is returned. Mostly everything related to that is described here http://fatfreeframework.com/databases#querying-the-database
If you're looking for errors or you want to know what has been executed, use
$db->log();
. http://fatfreeframework.com/databases#profilingDB querying
There are 3 variants to loop through db results:
Without mapper:
Execute a SQL query and fetch the result set as an array of associative arrays:
With mapper->load:
Fetch mapper rows one by one (your method):
With mapper->find:
Fetch the result set as an array of mappers:
DB error handling
\DB\SQL is a subclass of PDO so it can throw catchable PDO exceptions. Since these are disabled by default, you need to enable them first. This can be done in 2 different ways:
at instantiation time, for all transactions:
$db = new \DB\SQL($dsn, $user, $pwd, array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ));
later on in the code, on a per-transaction basis:
$db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Once PDO exceptions are enabled, just catch them as other exceptions:
This also works with DB mappers, since they rely on the same DB\SQL class: