To get a DB connection call $db = \Piwik\Db::get();
.
For a list of all available Db
methods and DbHelper
methods see our API reference. Below we will introduce some of these methods.
There are various methods available to query data like:
fetchOne
- return only one valuefetchRow
- return only one row as an arrayfetchAll
- return all matching rows as an arrayquery
- returns a Zend_Db_Statement which lets you iterate over each row, get the row count, and more.All of these support binding parameters using place holders (?
) for security to prevent SQL injections, for example:
$rows = $db->fetchAll('select * from log_visit where idvisit = ? and idsite = ?', [$idvisit, $idsite]);
foreach ($rows as $row) {
echo $row['idvisit'];
}
If you need to change data (insert, update, delete, alter), there are two methods you can use:
exec
- Executes an unprepared SQL query (no bound parameters can be used). Recommended for DDL statements like CREATE
, DROP
, LOCK
and ALTER
. The return value is DBMS-specific.query
- Executes a SQL query. This method is meant for non-query SQL statements like INSERT
, UPDATE
and DELETE
.Example:
$sql = sprintf('INSERT INTO table_name (`key`, `value`, `expiry_time`) VALUES (?,?,(UNIX_TIMESTAMP() + ?))';
$db->query($sql, array($key, $value, (int) $ttlInSeconds));
WHERE userername = "$var"
use WHERE userername = ?
and bind the value.WHERE idvisit = (int)$idvisit
.Learn more about adding new tables, columns, or indexes as well as how to update the DB schema in our dedicated extending the database guide.