Search code examples
phpfat-free-framework

Easiest way to retrieve a single field from database with Fat-Free Framework?


What is the easiest way to retrieve the value of a single field from a MySQL database using Fat-Free Framework? I have been able to do it with the following code which returns an array but am wondering how to improve this:

$result = $db->exec('SELECT id FROM admins WHERE username = ?',$f3->get('POST.username'));

This query returns the id field that we are seeking in an array which is accessible via $result[0]['id'] - can we avoid assigning this to an array and read it directly to a string variable?


Solution

  • I realise this is an old question but I ran into the same problem recently and came up with the findone() function. I wanted to share it as it had not been mentioned before in case anyone else is looking for a solution.

    $f3=\Base::instance();
    $f3->set('DB',new DB\SQL('sqlite:db/database.sqlite'));
    $admins = new \DB\SQL\Mapper($f3->get('DB'), 'admins');
    $username = $admins->findone(['username = ?', $f3->get('POST.username')])->username;
    

    Line 1-3 are just preliminaries. You'll need a table mapper to use this function. Line 4 is a one-liner which will set the $username to hold the actual value of the username.