
RedBeanPHP allows you to use good old SQL to find beans:
$needles = R::find('needle',' haystack = ? ',
array( $haystack )
);
The result of a find operation is an array of beans; the IDs are used as keys. Find takes 3 arguments; the type of bean you are looking for, the SQL query and an array containing the values to be used for the question marks. You can also use named slots in your queries:
$needles = R::find('needle',
' haystack = :haystack ORDER BY :sortorder',
array(
':sortorder'=>$sortorder,
':haystack'=>$haystack
)
);
Note that find() expects the SQL query to begin with the WHERE-clause. The 'WHERE' keyword should be omitted though. To find all needles:
$all = R::findAll('needle',
' ORDER BY title LIMIT 2 ');
You can use IN-clauses as well:
$all = R::find('needle',
' id IN ('.R::genSlots($ids).') ',$ids);
The little helper function genSlots() will add the correct number of question marks to the query string.
To find just one bean; use findOne():
$prod = R::findOne('product',
' code = ? ',array($code));
findOne will just return the first bean found.
There is no need to use mysql_real_escape as long as you use parameter binding. Use the question mark slots or the named slots as shown in the examples. Please don't use your own homebrewn escaping functions.
If no beans are found, find() returns an empty array array() and findOne() returns NULL.
RedBeanPHP 3.1 (and earlier) has no R::findAll, in this case you have to use the find() function. However, find() expects the SQL part to start with a WHERE-clause. So if you start with 'ORDER BY' the resulting SQL will be 'WHERE ORDER BY' which is incorrect. To avoid this start your WHERE-clause with 1 to simply select all records. Example: R::find('book',' 1 ORDER BY title ');
RedBeanPHP Easy ORM for PHP © 2013 Gabor de Mooij and the RedBeanPHP community - Licensed New BSD/GPLv2