Documentation

SQL

Presentation

If you have correctly configured the database connection parameters, Temma automatically creates an object of type \Temma\Base\Database. By convention, we will assume that you have named this connection db in the temma.json file (see the configuration documentation).

The connection is then available in the controller by writing:

$this->db

In the other objects managed by the dependency injection component, the connection to the database is accessible by writing:

$loader->dataSources['db']

Basic methods

exec
exec(string $sql) : void

The exec() method is used to execute queries for which no data is expected in return.
Examples:

// delete an article from its identifier
$this->db->exec("DELETE FROM article WHERE id = '12'");

// update the date of the last identification
// of all the users for whom this date is not defined
$sql = "UPDATE user
        SET lastLogin = NOW()
        WHERE lastLogin IS NULL";
$this->db->exec($sql);

queryOne
queryOne(string $sql) : array

The queryOne() method is used to execute queries for which we want to retrieve a row of data. The information is returned in the form of an associative array, whose keys correspond to the names of the fields in the table.

For example, the following code:

$sql = "SELECT * FROM article WHERE id = '11'";
$data = $this->db->queryOne($sql);
print_r($data);

Will give a result like this:

Array
(
    [id] => 11
    [status] => valid
    [title] => Title of the article
    [creationDate] => 2021-04-04 23:17:39
    [content] => Text of the article...
    [authorId] => 2
)

queryAll
queryAll(string $sql) : array

The queryAll() method is used to execute queries that return multiple rows of data. The information is retrieved in the form of a list each element of which is an associative array representing a row of data, the keys of which correspond to the names of the fields in the table.

For example, the following code:

$sql = "SELECT * FROM article WHERE authorId = '2'";
$data = $this->db->queryAll($sql);
print_r($data);

Donnera un résultat de ce genre :

Array
(
    [0] => Array
        (
            [id] => 11
            [status] => valid
            [title] => Title of the article
            [creationDate] => 2011-04-04 23:17:39
            [content] => Text of the article...
            [authorId] => 2
        )

    [1] => Array
        (
            [id] => 12
            [status] => valid
            [title] => Another title
            [creationDate] => 2011-04-05 20:34:20
            [content] => Another text...
            [authorId] => 2
        )

    [2] => Array
        (
            [id] => 16
            [status] => waiting
            [title] => Third article
            [creationDate] => 2011-04-10 11:03:44
            [content] => Some text...
            [authorId] => 2
        )
)

lastInsertId
lastInsertId(void) : int|string

The lastInsertId() method returns the primary key of the last record created on the current connection to the database.

Example of use:

// add an article to the database
$sql = "INSERT INTO article
        SET title = 'Titre', content = 'Texte', creationDate = NOW()";
$this->db->exec($sql);

// get the identifier of the new article
$id = $db->lastInsertId();

Escaping special characters

When writing SQL queries, be aware of the risk of SQL injection. To deal with it, you have to escape the special characters.

To do this, the \Temma\Base\Database object offers the quote() and quoteNull() methods.

These two methods take a text as a parameter, and return it after escaping each of its special characters. They add apostrophes at the beginning and at the end of the escaped text.

The quoteNull() method returns the string NULL (without apostrophes) if it has been given an empty string, a number equal to zero, or an empty array.

Examples:

$str = "You're the one";
$sql = "INSERT INTO article SET text = " . $db->quote($str);
// INSERT INTO ARTICLE SET text = 'You\'re the one'

$str = '';
$sql = "INSERT INTO article SET text = " . $db->quote($str);
// INSERT INTO article SET text = ''

$str = '';
$sql = "INSERT INTO article SET text = " . $db->quoteNull($str);
// INSERT INTO article SET text = NULL

Prepared requests

The \Temma\Base\Database object allows you to play queries prepared in advance, modifying only the parameters used at each execution.

The parameters can be provided in the form of a list, the elements of which replace the question marks placed in the query:

// prepare the request
$sql = "DELETE FROM article WHERE status = ? AND title != ?";
$statement = $db->prepare($sql);
// first execution
$statement->exec(['invalid', 'This one is good']);
// second execution
$statement->exec(['waiting', 'This one too']);

The parameters can be named in the query, and provided as an associative array:

// prepare the request
$sql = "DELETE FROM article WHERE status = :status AND title != :title";
$statement = $db->prepare($sql);
// first execution
$statement->exec([
    ':status' => 'invalid',
    ':title' => 'This one is good',
]);
// second execution
$statement->exec([
    ':status' => 'waiting',
    ':title' => 'This one too',
]);

In both cases, the parameters are automatically escaped (cf. methods quote() and quoteNull()).

It is also possible to use prepared queries to retrieve data. The queryOne() and queryAll() methods are used to retrieve a row of data and all the rows of data, respectively. The first returns an associative array whose keys are the column names; the second returns a list of associative arrays.
As with the exec() method, these methods can take a list of parameters, or an associative array of parameters.

// prepare the request
$sql = "SELECT * FROM article WHERE id = ?";
$statement = $db->prepare($sql);
// first read
$article1 = $statement->queryOne([12]);
// second read
$article2 = $statement->queryOne([23]);

// prepare the request
$sql = "SELECT * FROM article WHERE status = :status";
$statement = $db->prepare($sql);
// read
$articles = $statement->queryAll([':status' => 'invalid']);

Transactions management

The \Temma\Base\Database object provides two different ways to manage transactions.

Through an anonymous function, passed as a parameter to the transaction() method. If an exception is thrown in the anonymous function, an automatic rollback is performed; otherwise a commit is performed automatically at the end of the execution of the anonymous function.

// we create the transaction
// the anonymous function receives the connection
// to the database as a parameter
$this->db->transaction(function($db) use ($userId) {
    // we perform various requests
    $db->exec(...);
    $db->exec(...);
    $db->exec(...);
});

Or explicitly, using the startTransaction(), commit() and rollback() methods:

// we open a transaction
$this->db->startTransaction();

// we perform various requests
$this->db->exec(...);
$this->db->exec(...);
$this->db->exec(...);

// conditional processing
if ($something) {
    // the transaction is accepted
    $db->commit();
} else {
    // the transaction is canceled
    $db->rollback();
}
Previous: Model
Next: Redis

Table of Contents