2

How can i get the number of affected rows in drupal 7? db_affected_rows which i was used in d6 is not working in d7. It shows an error

 $bool = db_query("SELECT * FROM {template_config} WHERE user_role = ':d'",array(':d'=> $id));
        $num = db_affected_rows();
        if ($num != 0) {
            $result = db_fetch_array($bool);
            $custom_theme = $result['theme_name'];
        }

i want to check if there is any affected rows.db_num_rows also is not working in d7
How can i do this in d7?

migrated from stackoverflow.com Nov 14 '11 at 13:18

This question came from our site for professional and enthusiast programmers.

3

There is no db_affected_rows() in Drupal 7 I'm afraid. Also you don't need include the quotes in your variable placeholder. Your code might look a little more like this:

$results = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchAll();

if (count($results) > 0) {
  $first_result = $results[0];

  $custom_theme = $first_result->theme_name;
}

It could be even simpler though:

if ($result = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchObject()) {
  $custom_theme = $result->theme_name;
}
3

Drupal 7 is based on PDO as database abstraction layer. That's why a lot of functions have changed compared to D6. To get the number of affected rows, you can use the rowCount method.

By the way, in Drupal 7 you can simply foreach() over a database query result. When using foreach, you don't even need to check if the result has more than 0 rows. See db_query documentation for more info. The following example comes from that page:

<?php
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}
?>
2
$bool = db_query("SELECT * FROM {template_config} WHERE user_role = ':d'",array(':d'=> $id));
        $num = db_affected_rows($bool);

OR

$num = db_num_rows($bool);

    if ($num != 0) {
        $result = db_fetch_array($bool);
        $custom_theme = $result['theme_name'];
    }

Try this you have forgot passing the argument.

1

In drupal 7 use $pdos->rowCount(); to get the affected rows count.

$result = db_query('<your query>');
$affected_rows = $result->rowCount();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.