### Install RedBeanPHP using Curl and Signify
Source: https://redbeanphp.com/install
This command downloads the RedBeanPHP package, verifies its signature using signify, and extracts the contents. It's a streamlined way to get RedBeanPHP installed and secured.
```Shell
curl -L https://redbeanphp.com/downloadredbeanversion.php?f=all-drivers | signify -Vz -p ./red.pub -t arc | tar xvzf -
```
--------------------------------
### RedBeanPHP Setup and Connection
Source: https://redbeanphp.com/tutorial
This PHP code snippet shows how to include the RedBeanPHP library file (`rb.php`) and establish a database connection using the `R::setup()` function. This is the initial setup required before starting to code the application.
```PHP
require 'rb.php';
R::setup();
```
--------------------------------
### Install RedBeanPHP using Wget
Source: https://redbeanphp.com/install
This method uses wget to download the RedBeanPHP tarball and then extracts it using the tar command. It's a common approach for downloading files from the command line.
```Shell
url=http://www.redbeanphp.com/downloadredbean.php
wget $url --output-document="redbeanphp.tar.gz"
tar xvf redbeanphp.tar.gz
```
--------------------------------
### Installing a Legacy Plugin (Cooker)
Source: https://redbeanphp.com/index_p=%2Fplugins_create_your_own
This example illustrates the simple process of installing a legacy RedBeanPHP plugin, such as the 'Cooker' plugin. For many legacy plugins, simply including the plugin file automatically registers its functions with the R-facade.
```PHP
require 'plugins/Cooker/Cooker.php';
```
--------------------------------
### Activating a Custom Query Writer (DB2 Example)
Source: https://redbeanphp.com/index_p=%2Fplugins_create_your_own
This example demonstrates how to activate a custom Query Writer for a specific database, in this case, DB2. It involves including the writer's file and then using a specific setup method provided by the writer.
```PHP
// For instance to install DB2 database support
require 'db2.php';
R::setupDB2($dsn, $user, $pass);
```
--------------------------------
### RedBeanPHP Composer Installation
Source: https://redbeanphp.com/install
This JSON snippet shows how to add RedBeanPHP as a dependency in your composer.json file for installation via Composer. Note that this is not the preferred installation method.
```JSON
{
"require": {
"gabordemooij/redbean": "dev-master"
}
}
```
--------------------------------
### Get RedbeanPHP Toolbox
Source: https://redbeanphp.com/api/files/Facade
Retrieves the RedbeanPHP toolbox instance. The toolbox can be created using Setup::kickstart() or manually via the ToolBox class.
```PHP
public static function getToolBox()
{
return self::$toolbox;
}
```
--------------------------------
### Get RedBeanPHP Toolbox
Source: https://redbeanphp.com/api/classes/R
Returns the toolbox currently used by the facade. The toolbox can be set using R::setup() or R::configureFacadeWithToolbox(), or created using Setup::kickstart() or the ToolBox class.
```PHP
R::getToolBox()
```
--------------------------------
### Complete RedBeanPHP Example with Table Prefixes
Source: https://redbeanphp.com/prefixes
A comprehensive example illustrating the use of table prefixes in RedBeanPHP. It includes defining constants for tables, bypassing schema checks, renaming association tables, and demonstrating CRUD operations with prefixed tables and relations.
```PHP
//Define your mappings like this
define( 'POEM', 'tbl_poem' );
define( 'BOOK', 'tbl_book' );
define( 'AUTHOR', 'tbl_author' );
define( 'CATEGORY', 'tbl_category' );
define( 'POEMS', 'ownTblPoem' );
define( 'CATEGORIES', 'sharedTblCategory' );
//Create an extension to by-pass security check in R::dispense
R::ext('xdispense', function( $type ){
return R::getRedBean()->dispense( $type );
});
//Use tbl_book_category instead of tbl_book_tbl_category
R::renameAssociation([
'tbl_book_tbl_category' => 'tbl_book_category'
]);
//Use them like this:
$poem = R::xdispense( POEM );
$poem->title = 'Trees';
$author = R::xdispense( AUTHOR );
$author->name = 'Joyce Kilmer';
$book = R::xdispense( BOOK );
$book->title = 'Trees and other poems';
$category = R::xdispense( CATEGORY );
$category->name = 'nature';
$book->{AUTHOR} = $author;
$book->{POEMS}[] = $poem;
$book->{CATEGORIES}[] = $category;
$id = R::store( $book );
//For testing purposes let's output something:
$book = R::load( BOOK, $id );
$poem = reset( $book->{POEMS} );
$author = $book->{AUTHOR};
$category = reset( $book->{CATEGORIES} );
echo "Have you ever read '{$poem->title}' ({$book->title}) by {$author->name} ?
it's a beautiful poem about {$category->name}.";
```
--------------------------------
### Check RedBeanPHP Authenticity with Signify
Source: https://redbeanphp.com/install
This command verifies the authenticity of the RedBeanPHP archive using the signify tool and a public key. It ensures the downloaded file is from a trusted source and has not been tampered with.
```Shell
cat redbean.tgz | signify -Vz -p red.pub -t arc | tar xvzf -
```
--------------------------------
### Start Logging and Get Logs (PHP)
Source: https://redbeanphp.com/database
Enables and retrieves database query logs. R::startLogging() begins logging queries, and R::getLogs() returns the collected logs.
```PHP
R::startLogging(); //start logging
$logs = R::getLogs(); //obtain logs
```
--------------------------------
### Include RedBeanPHP in PHP Project
Source: https://redbeanphp.com/install
This PHP code snippet demonstrates how to include the RedBeanPHP library (rb.php) into your project using the 'require' statement, making its ORM functionalities available.
```PHP
require 'rb.php';
```
--------------------------------
### Start Logging and Get Logs (PHP)
Source: https://redbeanphp.com/index_p=%2Fdatabase
Enables and retrieves database query logs. R::startLogging() begins logging queries, and R::getLogs() returns the collected logs.
```PHP
R::startLogging(); //start logging
$logs = R::getLogs(); //obtain logs
```
--------------------------------
### Setup MySQL Database Connection in RedBeanPHP
Source: https://redbeanphp.com/quick_tour
Provides an example of establishing a persistent connection to a MySQL database using RedBeanPHP. This includes specifying the database host, name, username, and password.
```PHP
R::setup( 'mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassword' );
```
--------------------------------
### Extract RedBeanPHP Tarball
Source: https://redbeanphp.com/install
This command is used to extract the contents of the RedBeanPHP tarball (TGZ package) into the current directory, making the rb.php file available.
```Shell
tar xvf redbeanphp.tar.gz
```
--------------------------------
### Direct PDO Connection Example
Source: https://redbeanphp.com/connection
Demonstrates how to establish a direct PDO connection to a database. This is useful for debugging connection errors, as RedBeanPHP may suppress PDO errors for security reasons. It includes a try-catch block to display any PDO exceptions.
```PHP
try{
$db = new PDO('mysql:host=HOSTNAME;dbname=DB_NAME','USERNAME','PASSWORD');
} catch(PDOException $e){
echo $e->getmessage();
}
```
--------------------------------
### Connect to CUBRID
Source: https://redbeanphp.com/connection
Connects to a CUBRID database, an alternative to MySQL with advanced features. Ensure you have the CUBRID plugin pack installed for RedBeanPHP4. Replace connection details as needed.
```PHP
R::setup('cubrid:host=localhost;port=30000;
dbname=mydatabase',
'user','password');
```
--------------------------------
### RedBeanPHP OODB Constructor and Usage Example
Source: https://redbeanphp.com/api/classes/RedBeanPHP.QueryWriter
This PHP code demonstrates the constructor for the RedBeanPHP OODB (Object-Oriented Database) class and provides a usage example. It shows how to manually wire the core RedBeanPHP objects (Adapter, Query Writer, OODB) and perform basic operations like dispensing, storing, and loading beans.
```PHP
public function __construct( Adapter $adapter )
{
$this->typeno_sqltype = array(
SQLiteT::C_DATATYPE_INTEGER => 'INTEGER',
SQLiteT::C_DATATYPE_NUMERIC => 'NUMERIC',
SQLiteT::C_DATATYPE_TEXT => 'TEXT',
);
$this->sqltype_typeno = array();
foreach ( $this->typeno_sqltype as $k => $v ) {
$this->sqltype_typeno[$v] = $k;
}
$this->adapter = $adapter;
$this->adapter->setOption( 'setInitQuery', ' PRAGMA foreign_keys = 1 ' );
}
/**
* Usage:
*
* $database = new RPDO( $dsn, $user, $pass );
* $adapter = new DBAdapter( $database );
* $writer = new PostgresWriter( $adapter );
* $oodb = new OODB( $writer, FALSE );
* $bean = $oodb->dispense( 'bean' );
* $bean->name = 'coffeeBean';
* $id = $oodb->store( $bean );
* $bean = $oodb->load( 'bean', $id );
*
*/
```
--------------------------------
### RedBeanPHP PoolDB Plugin Usage Example
Source: https://redbeanphp.com/api/classes/RedBeanPHP.Plugin
Demonstrates how to add multiple databases to a pool, nuke them, dispense and store beans in specific databases, and retrieve beans from their original databases. This example highlights the core functionality of the PoolDB plugin.
```PHP
toolbox;
return array( $toolbox->getRedbean(), $toolbox->getDatabaseAdapter(), $toolbox->getWriter(), $toolbox );
}
/**
* Constructor
*
* Creates a new instance of the NonStaticBeanHelper.
* The NonStaticBeanHelper is used by the database pool class PoolDB.
*/
public function __construct($toolbox)
{
$this->toolbox = $toolbox;
}
}
/**
* PoolDB
*
* Represents a pool of databases that will have persisting
* associations with the beans they dispense. Saving a bean from
* a pooled database will make sure that the bean will be stored
* in the database it originated from instead of the currently
* selected database.
*
* @experimental
* This is an experimental plugin, added for testing purposes
* only.
*
* Usage:
*
*
* // Let's add some databases
* R::addPoolDatabase( 'db1', 'sqlite:/tmp/db1.txt' );
* R::nuke();
* R::addPoolDatabase( 'db2', 'sqlite:/tmp/db2.txt' );
* R::nuke();
* R::addPoolDatabase( 'db3', 'sqlite:/tmp/db3.txt' );
* R::nuke();
*
* // create a book and page in db1
* R::selectDatabase('db1');
* $book = R::dispense(array(
* '_type' => 'book',
* 'title' => 'Databases for Beans',
* 'ownPageList' => array(
* 0 => array(
* '_type' => 'page',
* 'content' => 'Lorem Ipsum'
* )
* )
* ));
* R::store($book);
*
* //switch to db2
* R::selectDatabase( 'db2' );
* //obtain pages (from db1)
* $pages = count($book->ownPageList);
* echo "I found {$pages} pages in db1.\n";
*
* $pages = R::count('page');
* echo "There are {$pages} pages in db2.\n";
*
* // create pizza in db 2
* $pizza = R::dispense('pizza');
*
* // switch to db3
* R::selectDatabase( 'db3' );
*
* // store pizza in db2
* $pizza->pepperoni = true;
* R::store($pizza);
*
* $pizzas = R::count('pizza');
* echo "There are {$pizzas} in pizzas db3.\n";
* R::selectDatabase('db2');
* $pizzas = R::count('pizza');
* echo "There are {$pizzas} pizzas in db2.\n";
*
*
* @file RedBeanPHP/Plugin/Pool.php
* @author RedBeanPHP Community
* @license BSD/GPLv2
*
* @copyright
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class PoolDB extends OODB {
/**
* @var array
*/
private static $pool = array();
/**
* @var ToolBox
*/
private $toolbox;
/**
* @var OODB
*/
private $oodb;
/**
* @var string
*/
private $key;
/**
* @var NonStaticBeanHelper
*/
private $beanHelper;
/**
* Constructor
*
* creates a new instance of the database pool.
*
* @param string $key key
* @param OODB $oodb oodb instance
*/
public function __construct( $key, $oodb)
{
self::$pool[$key] = $oodb;
$this->oodb = $oodb;
$this->key = $key;
parent::__construct( $oodb->writer, $oodb->isFrozen );
}
/**
* Sets the toolbox to be used by the database pool.
*
* @param ToolBox $toolbox toolbox
*
* @return void
*/
public function setToolBox( $toolbox )
{
$this->toolbox = $toolbox;
$this->beanHelper = new NonStaticBeanHelper( $this->toolbox );
$this->beanHelper->key = $this->key;
$this->oodb->setBeanHelper( $this->beanHelper );
}
/**
* Returns the bean helper of the database pool.
*
* @return BeanHelper
*/
public function getBeanHelper()
{
return $this->beanHelper;
}
/**
* Implements the find operation.
*
* @see OODB::find
*/
public function find( $type, $conditions=array(), $sql=NULL, $bindings=array())
{
return parent::find($type, $conditions, $sql, $bindings);
}
/**
* Dispenses a new bean from the database pool.
* A bean that has been dispensed by the pool will have a special
* meta attribute called sys.source containing the key identifying
* the database in the pool it originated from.
*
* @see OODB::dispense
*/
public function dispense( $type, $number = 1, $alwaysReturnArray = FALSE )
{
$bean = $this->oodb->dispense( $type, $number, $alwaysReturnArray );
foreach( self::$pool as $key => $db ) {
if ( $this->oodb === $db ) {
$bean->setMeta( 'sys.source',$key );
}
}
return $bean;
}
/**
* Stores the specified bean in the database in the pool
* it originated from by looking up the sys.source attribute.
*
* @see OODB::store
*/
public function store( $bean )
{
```
--------------------------------
### Apply Patch for PHP 5.3.3 and Earlier
Source: https://redbeanphp.com/install
This command executes a PHP script that patches RedBeanPHP for compatibility with older PHP versions (5.3.3 and earlier). It generates a new file, rb-p533.php, for use with these versions.
```Shell
php p533patch.php
```
--------------------------------
### Create and Edit Application File
Source: https://redbeanphp.com/tutorial
This snippet demonstrates creating a new PHP file named `dram.php` using the `touch` command and opening it for editing with the `vim` text editor. This file will contain the application logic.
```Shell
touch dram.php
vim dram.php
```
--------------------------------
### PHP: Get Command Line Options
Source: https://redbeanphp.com/tutorial
This snippet uses PHP's getopt() function to parse command-line arguments, specifically listening for 'add', 'list', and 'delete' commands with optional values.
```PHP
$opts = getopt( '', [ 'add:', 'list' ] );
```
```PHP
$opts = getopt( '', ['add:', 'list', 'delete:' ] );
```
--------------------------------
### RedBeanPHP Initialization and Core Loading
Source: https://redbeanphp.com/api4/source-class-R
This snippet demonstrates the initialization process for RedBeanPHP, including defining the main directory, loading database drivers, infrastructure components, adapters, SQL drivers, exceptions, repositories, core functionalities, and extended features. It also includes utility functions and developer comfort tools.
```php
$frozen = FALSE, boolean|array $partialBeans = FALSE, array $options = array()) : \RedBeanPHP\ToolBox
```
--------------------------------
### Bash: Execute PHP Script
Source: https://redbeanphp.com/tutorial
Examples of executing the PHP script 'dram.php' from the command line with different arguments to add, list, or delete whisky records.
```Bash
php dram.php --add="Bowmore 12yo"
OK.
```
```Bash
php dram.php --add="Lagavulin 16yo"
OK.
```
```Bash
php dram.php --list
* #1: Bowmore 12yo
* #2: Lagavulin 16yo
```
```Bash
php dram.php --delete=3
Threw the bottle away!
```
```Bash
php dram.php --add="Dailuaine 16yo"
```
--------------------------------
### RedBeanPHP Initialization and Core Loading
Source: https://redbeanphp.com/api4/source-class-RedBean_SimpleModel
This snippet demonstrates the initialization process for RedBeanPHP, including defining the main directory, loading database drivers, infrastructure components, adapters, SQL drivers, exceptions, repositories, core functionalities, and extended features. It also includes utility functions and developer comfort tools.
```php
```
--------------------------------
### Start Query Logging with RedBeanPHP
Source: https://redbeanphp.com/api/classes/R
The startLogging() method enables the logging of SQL queries executed by RedBeanPHP. Logs can be retrieved using R::getLogs() and are not printed directly.
```php
R::startLogging();
R::store( R::dispense( 'book' ) );
R::find('book', 'id > ?',[0]);
$logs = R::getLogs();
$count = count( $logs );
print_r( $logs );
R::stopLogging();
```
--------------------------------
### RedbeanPHP CLI Application for Whisky Management (PHP)
Source: https://redbeanphp.com/tutorial
This comprehensive PHP script utilizes RedbeanPHP to manage a collection of whisky bottles via a command-line interface. It supports adding new bottles, deleting bottles, attaching tasting notes to specific bottles, listing all notes for a bottle, removing notes, and listing all available bottles. The script uses `getopt` to parse command-line arguments and RedbeanPHP functions like `dispense`, `store`, `load`, `trash`, and `find`.
```php
require 'rb.php';
R::setup();
$opts = getopt( '', [
'add:',
'delete:',
'attach-to:',
'note:',
'notes:',
'remove-note:',
'list' ] );
if ( isset( $opts [ 'add' ] ) ) {
$w = R::dispense( 'whisky' );
$w->name = $opts['add'];
$id = R::store( $w );
die( "OK.\n" );
}
if ( isset( $opts['delete'] ) ) {
R::trash( 'whisky', $opts['delete'] );
die( "Threw the bottle away!\n" );
}
if ( isset( $opts['note'] ) && isset( $opts['attach-to'] ) ) {
$w = R::load( 'whisky', $opts['attach-to'] );
if (!$w->id) die( "No such bottle.\n" );
$n = R::dispense( 'note' );
$n->note = $opts['note'];
$w->xownNoteList[] = $n;
R::store( $w );
die( "Added note to whisky.\n" );
}
if ( isset( $opts['notes'] ) ) {
$w = R::load( 'whisky', $opts['notes'] );
foreach( $w->xownNoteList as $note ) {
echo "* #{$note->id}: {$note->note}\n";
}
exit;
}
if ( isset( $opts['remove-note'] ) ) {
R::trash( 'note', $opts['remove-note'] );
die( "Removed note.\n" );
}
if ( isset( $opts['list'] ) ) {
$bottles = R::find( 'whisky' );
if ( !count( $bottles ) ) die( "The cellar is empty!\n" );
foreach( $bottles as $b ) {
echo "* #{$b->id}: {$b->name}\n";
}
exit;
}
```
--------------------------------
### Get RedBeanPHP Logs
Source: https://redbeanphp.com/api/classes/R
Retrieves log entries generated after starting the logging mechanism. This method is useful for inspecting query logs without printing them to the screen. Ensure logging is stopped only after obtaining the logs.
```PHP
R::startLogging();
R::store( R::dispense( 'book' ) );
R::find('book', 'id > ?',[0]);
$logs = R::getLogs();
$count = count( $logs );
print_r( $logs );
R::stopLogging();
```
--------------------------------
### RedBeanPHP: Using alias() for Related Beans
Source: https://redbeanphp.com/aliases
Illustrates how to use the `alias` method in RedBeanPHP to retrieve a list of related beans where the relationship is defined through an alias. This example shows how to get all courses where a specific person acts as the 'teacher'.
```PHP
//returns all courses for this person
//where he/she is the teacher.
$person->alias( 'teacher' )->ownCourseList;
```
--------------------------------
### Create RedBeanPHP Toolbox
Source: https://redbeanphp.com/api/classes/R
Creates a RedBeanPHP toolbox for non-static usage, similar to R::setup(). It supports various database types and lazy connection initialization. The function can be called with or without arguments; if no arguments are provided, it attempts to create a SQLite database in /tmp.
```PHP
```
--------------------------------
### PHP: Using alias for Related Bean Lists
Source: https://redbeanphp.com/one_to_fixed
Illustrates how to use the `alias` method in RedBeanPHP to retrieve a list of related beans based on an aliased relationship. This example shows how to get all 'course' beans where a specific 'person' acts as the 'teacher'.
```PHP
//returns all courses for this person
//where he/she is the teacher.
$person->alias( 'teacher' )->ownCourseList;
```
--------------------------------
### Get Insert ID from RedBeanPHP Adapter
Source: https://redbeanphp.com/api4/source-class-RedBeanPHP.Adapter
Retrieves the ID of the last inserted row. This is useful after performing an insert operation to get the newly generated primary key.
```PHP
public function getInsertID()
{
return $this->db->getInsertID();
}
```
--------------------------------
### Configure RedBeanPHP Facade with ToolBox
Source: https://redbeanphp.com/api/files/Facade
Allows hot-swapping the facade's components (Writer, Adapter, RedBean instance) on-the-fly by providing a new ToolBox. This is useful for dynamic configuration changes.
```PHP
public static function configureFacadeWithToolbox( ToolBox $tb )
{
$oldTools = self::$toolbox;
self::$toolbox = $tb;
self::$writer = self::$toolbox->getWriter();
self::$adapter = self::$toolbox->getDatabaseAdapter();
self::$redbean = self::$toolbox->getRedBean();
self::$finder = new Finder( self::$toolbox );
self::$associationManager = new AssociationManager( self::$toolbox );
sself::$tree = new Tree( self::$toolbox );
sself::$redbean->setAssociationManager( self::$associationManager );
sself::$labelMaker = new LabelMaker( self::$toolbox );
$helper = new SimpleModelHelper();
$helper->attachEventListeners( self::$redbean );
if (self::$redbean->getBeanHelper() === NULL) {
self::$redbean->setBeanHelper( new SimpleFacadeBeanHelper );
}
sself::$duplicationManager = new DuplicationManager( self::$toolbox );
sself::$tagManager = new TagManager( self::$toolbox );
return $oldTools;
}
```
--------------------------------
### Get All Tables
Source: https://redbeanphp.com/api/classes/RedBeanPHP.QueryWriter
Retrieves a list of all table names from the database. It queries the 'sqlite_master' table to get names of all entries with type 'table', excluding 'sqlite_sequence'.
```PHP
public function getTables()
{
return $this->adapter->getCol( "SELECT name FROM sqlite_master
WHERE type='table' AND name!='sqlite_sequence';" );
}
```
--------------------------------
### PHP: List Whisky Records
Source: https://redbeanphp.com/tutorial
This PHP snippet lists all whisky records from the database using RedBeanPHP's find() method. It iterates through the found bottles and prints their ID and name.
```PHP
if ( isset( $opts['list'] )) {
$bottles = R::find( 'whisky' );
if ( !count( $bottles ) )
die( "The cellar is empty!\n" );
foreach( $bottles as $b ) {
echo "* #{$b->id}: {$b->name}\n";
}
exit;
}
```
--------------------------------
### Connect to SQLite (Testing)
Source: https://redbeanphp.com/connection
Establishes a connection to an SQLite testing database, creating a test database in the /tmp folder. This is primarily for testing and demonstration purposes.
```PHP
require 'rb.php';
R::setup();
```
--------------------------------
### Get Last Insert ID with RedBeanPHP
Source: https://redbeanphp.com/api/files/Driver
Retrieves the ID of the last inserted row from the database using RedBeanPHP. It ensures the connection is established before attempting to get the last insert ID.
```PHP
public function GetInsertID()
{
$this->connect();
return (int) $this->pdo->lastInsertId();
}
```
--------------------------------
### List Tasting Notes for a Whisky (PHP)
Source: https://redbeanphp.com/tutorial
This code snippet demonstrates how to retrieve and display all tasting notes associated with a specific whisky bottle using RedbeanPHP. It accesses the 'xownNoteList' property of the whisky bean, which contains all related 'note' beans, and then iterates through them to print the 'note' property of each.
```php
$notes = $whisky->xownNoteList;
foreach( $notes as $note ) echo $note->note;
```
--------------------------------
### Get Table Columns
Source: https://redbeanphp.com/api/classes/RedBeanPHP.QueryWriter
Retrieves the column information for a given table. It executes a PRAGMA command to get column details and returns an associative array mapping column names to their types.
```PHP
public function getColumns( $table )
{
$table = $this->esc( $table, TRUE );
$columnsRaw = $this->adapter->get( "PRAGMA table_info('$table')" );
$columns = array();
foreach ( $columnsRaw as $r ) $columns[$r['name']] = $r['type'];
return $columns;
}
```
--------------------------------
### Get Last Insert ID with RedBeanPHP
Source: https://redbeanphp.com/api/classes/RedBeanPHP.Driver
Retrieves the ID of the last inserted row from the database using RedBeanPHP. It ensures the connection is established before attempting to get the last insert ID.
```PHP
public function GetInsertID()
{
$this->connect();
return (int) $this->pdo->lastInsertId();
}
```
--------------------------------
### SQL: Show Whisky Table Schema
Source: https://redbeanphp.com/tutorial
This SQL command displays the schema of the 'whisky' table created by RedBeanPHP, showing the 'id' (primary key) and 'name' columns.
```SQL
sqlite> .schema
CREATE TABLE `whisky` (
id INTEGER PRIMARY KEY AUTOINCREMENT ,
`name` TEXT
);
```
--------------------------------
### RedBeanPHP: Many-to-Many Shared List Example
Source: https://redbeanphp.com/many_to_many
Demonstrates how to establish a many-to-many relationship using a shared list in RedBeanPHP. This example creates a 'product' and 'tag' and associates them, automatically creating a 'product_tag' link table.
```PHP
list($vase, $lamp) = R::dispense('product', 2);
$tag = R::dispense( 'tag' );
$tag->name = 'Art Deco';
//creates product_tag table!
$vase->sharedTagList[] = $tag;
$lamp->sharedTagList[] = $tag;
R::storeAll( [$vase, $lamp] );
```
--------------------------------
### PHP: Add Whisky Record
Source: https://redbeanphp.com/tutorial
This PHP code adds a new whisky record to the database using RedBeanPHP. It takes the whisky name from the command line, creates a new 'whisky' bean, sets its name, and stores it.
```PHP
if ( isset( $opts['add'] ) ) {
$w = R::dispense( 'whisky' );
$w->name = $opts['add'];
$id = R::store( $w );
die( "OK.\n" );
}
```
--------------------------------
### RedBeanPHP Tree: Constructor
Source: https://redbeanphp.com/api/classes/RedBeanPHP.Util
Initializes a new instance of the RedBeanPHP Tree utility class. The constructor requires a RedBeanPHP ToolBox object to be passed, which provides access to the database and other necessary components.
```PHP
__construct(RedBeanPHP\ToolBox $toolbox)
```
--------------------------------
### RedbeanPHP: Start Query Logging
Source: https://redbeanphp.com/api/files/Facade
Initiates the logging of SQL queries executed by the adapter. Logs are not displayed on screen and can be retrieved using R::getLogs(). Note that this cannot be used simultaneously with R::debug.
```PHP
public static function startLogging()
{
self::debug( TRUE, RDefault::C_LOGGER_ARRAY );
}
```
--------------------------------
### PHP RedBeanPHP Transaction Example
Source: https://redbeanphp.com/api4/class-RedBeanPHP.Util
This example demonstrates how to use the RedBeanPHP Transaction class to wrap a series of database operations within a transaction. It shows loading beans, modifying their properties, and storing them, with automatic commit or rollback based on exceptions.
```PHP
R::transaction(function() use($from, $to, $amount)
{
$accountFrom = R::load('account', $from);
$accountTo = R::load('account', $to);
$accountFrom->money -= $amount;
$accountTo->money += $amount;
R::store($accountFrom);
R::store($accountTo);
});
```
--------------------------------
### Select RedBeanPHP Database
Source: https://redbeanphp.com/api/classes/R
Selects a different database for the RedBeanPHP Facade to work with, primarily for multi-database setups. It takes a database key and an optional force parameter. If R::setup() was used, the default database is stored under the key 'default'.
```PHP
```
--------------------------------
### RedBeanPHP Tree: Get Parent Beans
Source: https://redbeanphp.com/api/classes/RedBeanPHP.Util
Retrieves all parent beans associated with a given bean in a tree structure. Similar to getting children, this functionality depends on the database's support for recursive common table expressions. Custom SQL and bindings can be used for advanced querying.
```PHP
R::parents( $newsArticle, ' ORDER BY title ASC ' );
R::parents( $newsArticle, ' WHERE title = ? ', [ $t ] );
R::parents( $newsArticle, ' WHERE title = :t ', [ ':t' => $t ] );
```
--------------------------------
### Configure RedBeanPHP Facade with Toolbox
Source: https://redbeanphp.com/api/classes/R
Allows dynamic configuration of the RedBeanPHP facade by providing a new ToolBox instance. This is useful for hot-swapping components like the Writer, Object Database, or Adapter.
```PHP
configureFacadeWithToolbox(RedBeanPHPToolBox $tb) : RedBeanPHPToolBox
```
--------------------------------
### RedBeanPHP DBAdapter Get SQL
Source: https://redbeanphp.com/api4/class-RedBeanPHP.Adapter
Retrieves the SQL string from the DBAdapter.
```PHP
public function getSQL(): string
```