Accessing the Database to Make Queries

Making a custom database query in concrete5 is easy. This can be done from within any method, controller, or even a view (although not recommended). To retrieve the database object, simply call this function:

\Database::connection();

Example

public static function getFoo($id)
{
    $db = \Database::connection();
    $foo = $db->fetchColumn('SELECT foo FROM bar WHERE id = ?', [$id]);
    return $foo;
}

Note how the $id is passed in as the second parameter rather than simply appended to the string. This makes use of Prepared Statements to avoid potential SQL injection issues.

Doctrine API

Concrete5's database class is based heavily on the Doctrine DBAL Connection object.

The list of Doctrine functions is available at:
http://www.doctrine-project.org/api/dbal/2.1/class-Doctrine.DBAL.Connection.html

DBAL's advanced features like auto-quoting, placeholders, UPDATE and DELETE queries are explained at:
http://doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html

Deprecated Methods

You may see code like Loader::db() – or Database::get(). These particular methods of obtaining the database connection are deprecated and should not be used in new code. Use \Database::connection(); instead.

Advanced: Using Dependency Injection

New in version 5.7.5.4

If you're working on a custom class and you'd like the active database connection passed into the class, rather than calling this method from within your class methods, define the database connection as as parameter in your class constructor like this:

namespace My\Custom\Name;
use Concrete\Core\Database\Connection\Connection;

class Bar
{

    protected $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    public function getFoo($id)
    {
        $foo = $this->connection->fetchColumn('SELECT foo FROM bar WHERE id = ?', [$id]);
        return $foo;
    }

}

By using the Core::make() method to instantiate your custom object, the dependencies like Connection will automatically be populated.

    $bar = Core::make('My\Custom\Name\Bar');
    $foo = $bar->getFoo(12);

Even though we didn't instantiate the class directly and pass the active connection in, the Core::make() method is able to intelligently instantiate and provide the necessary objects to the constructor.

Loading Conversation