How do I loop through the mysql resultset in fatfree framework?

六眼飞鱼酱① 提交于 2019-12-01 01:06:36

DB 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:

$users = $db->exec('SELECT * FROM users');
foreach($users as $user)
  echo $user['name'];//associative array

With mapper->load:

Fetch mapper rows one by one (your method):

$user=new \DB\SQL\Mapper($db,'users');
$user->load('');
while(!$user->dry()) {
  echo $user->name;//db mapper
  $user->next();
}

With mapper->find:

Fetch the result set as an array of mappers:

$mapper=new \DB\SQL\Mapper($db,'users');
$users=$mapper->find('');
foreach($users as $user)
  echo $user->name;//db mapper

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:

try {
  $db->exec('INSERT INTO mytable(id) VALUES(?)','duplicate_id');
} catch(\PDOException $e) {
  $err=$e->errorInfo;
  //$err[0] contains the error code (23000)
  //$err[2] contains the driver specific error message (PRIMARY KEY must be unique)
}

This also works with DB mappers, since they rely on the same DB\SQL class:

$db=new \DB\SQL($dsn,$user,$pwd,array(\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION));
$mytable=new \DB\SQL\Mapper($db,'mytable');
try {
  $mytable->id='duplicate_id';
  $mytable->save();//this will throw an exception
} catch(\PDOException $e) {
  $err=$e->errorInfo;
  echo $err[2];//PRIMARY KEY must be unique
}

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

$result = $db->exec('SELECT * FROM users'); 
print_r($result);

If you're looking for errors or you want to know what has been executed, use $db->log();. http://fatfreeframework.com/databases#profiling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!