DB beállítás a sites/default/settings.php fájlban:
$db_url = 'mysql://username:password@localhost/databasename';
Néhány lekérdezés (CRUD):
db_query('SELECT * FROM {joke} WHERE vid = %d', $node->vid);
db_query("INSERT INTO {joke} (nid, vid, punchline) VALUES
(%d, %d, '%s')", $node->nid, $node->vid, $node->punchline);
db_query("UPDATE {joke} SET punchline = '%s' WHERE vid = %d",
$node->punchline, $node->vid);
db_query('DELETE FROM {joke} WHERE nid = %d', $node->nid);
Helyettesítők:
%s - String
Egyszerű érték lekérdezése:
%d - Integer
%f - Float
%b - Binary data; do not enclose in ' '
%% - % jel
$sql = "SELECT COUNT(*) FROM {node} WHERE type = 'blog'
Sorok lekérdezése:
AND status = 1";
$total = db_result(db_query($sql));
$sql = "SELECT * FROM {node} WHERE type = 'blog' AND status=1";
Limit:
$result = db_query(db_rewrite_sql($sql));
while ($data = db_fetch_object($result)) {
$node = node_load($data->nid);
print node_view($node, TRUE);
}
$sql = "SELECT * FROM {node} n WHERE type = 'blog'
Dinamikus paraméterezés:
AND status = 1 ORDER BY n.created DESC";
$result = db_query_range(db_rewrite_sql($sql), 0, 10);
$type = 'blog';
Lapozás (nem az API része):
$status = 1;
$sql = "SELECT * FROM {node} n WHERE type = '%s' AND status = %d
ORDER BY n.created DESC";
$result = db_query_range(
db_rewrite_sql($sql), $type, $status, 0, 10
);
$sql = "SELECT * FROM {node} n WHERE type = 'blog'
Több adatbázis használata:
AND status = 1 ORDER BY n.created DESC";
$result = pager_query(db_rewrite_sql($sql), 0, 10);
while ($data = db_fetch_object($result)) {
$node = node_load($data->nid);
print node_view($node, TRUE);
}
// Add links to remaining pages of results.
print theme('pager', NULL, 10);
$db_url['default'] = 'mysql://user:password@localhost/drupal5';
Adatbázis séma updateje. Az .install fájlban:
$db_url['legacy'] = 'mysql://user:password@localhost/legacydb';
...
db_set_active('legacy');
$result = db_query("SELECT * FROM ldap_user WHERE uid = %d",
$user->uid);
// Switch back to the default connection when finished.
db_set_active('default');
function book_update_1() {
$items = array();
$items[] = update_sql("ALTER TABLE {book}
ADD COLUMN rank int_unsigned NOT NULL default '0'");
}
(Az első update az _1-es, a második a_2-es, stb. A számot a system tábla tárolja.)
Uninstall. Az .install fájlban:
function annotate_uninstall() {
API függvények:
db_query("DROP TABLE {annotations}");
variable_del('annotate_nodetypes');
}
_db_query($query, $debug = 0)
db_affected_rows()
db_connect($url)
db_decode_blob($data)
db_distinct_field($table, $field, $query)
db_encode_blob($data)
db_error()
db_escape_string($text)
db_fetch_array($result)
db_fetch_object($result)
db_lock_table($table)
db_next_id($name)
db_num_rows($result)
db_query_range($query)
db_query_temporary($query)
db_result($result, $row = 0)
db_status_report($phase)
db_table_exists($table)
db_unlock_tables()
db_version()