开发者

How do I connect to the database from a Drupal 7 module?

开发者 https://www.devze.com 2023-03-10 04:36 出处:网络
I would like to connect to the database from a Drupal 7 module. Currently I only have the query I want to run which is:

I would like to connect to the database from a Drupal 7 module. Currently I only have the query I want to run which is:

$query = db_select('z_lists)
->fields('country')
->condition('value', $country, '=')
->execute()
-&g开发者_运维问答t;fetchAssoc();

What I can't figure out is how to establish a connection to the default database.

Any help?


In Drupal7 there is function called db_query(). you can use that function to run your queries. You can use below syntex

$var1 = 1;
$result = db_query('SELECT n.title FROM {node} n WHERE n.uid = :uid', array(':uid' => $var1));

$result will be stdClass object so you can use it in foreach loop.


The only problems with the op's example code was a misuse of the db_select and a missing single quote.

Dynamic queries: https://drupal.org/node/310075

It would have been fine if you'd just used this instead:

$query = db_select('z_lists','z')
    ->fields('z')
    ->condition('value', $country, '=')
    ->execute()
    ->fetchAssoc();

That would return all fields for the matching record(s).

the ->fetchAssoc() chained to the end would ensure you only received the first matching record. If you expected multiple results you'd leave off ->fetchAssoc() and just loop through the results with:

foreach($query as $result){
    ... do something with the data here ...
}

But to answer the actual ASKED question, you're automatically connected to the default database. There is no need to declare any kind of DB connection before running any kind of query to the site db.

If you're trying to connect to an external database that's a different issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消