- Getting started
- Basics
- Finding
- Finding Beans
- Queries
- Mixing SQL and PHP
- Relation Mapping
- Models
- Database
- BeanCan
- Advanced
- Architecture
- Other
Mixing SQL and PHP
In RedBeanPHP you can mix PHP and SQL as if it were just one language. To call an SQL function in PHP simply call it like a PHP function on R::$f. $f is short for 'function' and we mean SQL function here. Here are some examples:
$time = R::$f->now(); //executes and returns result of: SELECT NOW();
Besides simple SQL functions like now() you can build queries that blend perfectly with your PHP code. This is useful for writing complex dynamic queries. This technique allows you to share queries among functions and methods just like a query builder does. The only difference is, you don't need to learn a new syntax, it's plain old SQL!
R::$f->begin()
->select('*')->from('bean')
->where(' field1 = ? ')->put('a')->get('row');
This PHP code is the equivalent of:
select * from bean where field1 = 'a'
There are just a couple of rules. First, you must begin a PHP-SQL query that is longer than just one SQL function with the begin() method. This method prepares the SQL helper for a query. Now you can chain SQL statements as PHP function calls. To add a value to the parameter list use put(), finally you must end the query with get(), get('row'), get('col') or get('cell'). These methods are similar to the default database adapter methods found elsewhere in RedBeanPHP. Thus get() will return a multi dimensional array with each row containing an associative array (column=>value), while get('row') returns just one such row. Analogous get('col') returns a flat array of the column values and get('cell') returns a single value.
Since RedBeanPHP 3.2: Underscores will be replaced by spaces.
Tweet
User contributed notes. Please use the comment section to provide tips, notes and examples. To ask for support or to provide feedback use the forum. For bug reports use Github Issue Tracker.
Site comments powered by Disqus