1

I wrote db_query in two ways, I followed the drupal documentation to write safe db_query, one of them doesn't work, I want to know what I'm doing wrong in the code below.

// Worked perfectly
function custom_get_user_account_id() {
  global $user;
  return db_query("SELECT `field_account_target_id` FROM {field_data_field_account} where `entity_id`=:user_id and `bundle` = 'user'", array('user_id' => $user->uid))->fetchField();
}

// doesn't work
function custom_get_user_account_id() {
  global $user;
  return db_query("SELECT field_account_target_id FROM {field_data_field_account} fa where 'fa.entity_id = :user_id and fa.bundle = :user' ", array(':user_id' => $user->uid, ':user' => 'user'))->fetchField();
}
  • Welcome to Drupal Answers! doesn't work is quite a broad statement that doesn't say what exactly didn't work. What error did you get? What result did you get? In which way was it different from what you expected to obtain? – kiamlaluno May 16 at 10:16
0

Supposing that the first version of the function is working, it doesn't restrict the values by the entity ID, since you aren't providing any value for the :user_id placeholder.

The second version of the function doesn't work because, instead of passing the 'user' string as value for the :user_id placeholder, it's passing an object which, if casted to a string, it's not surely equal to 'user'. Plus enclosing the fa.entity_id = :user_id and fa.bundle = :user in string delimiters is wrong, as it's making that part a literal string, which is not what you want.

The correct version of the function is the following one.

function custom_get_user_account_id() {
  global $user;
  return db_query("SELECT fa.field_account_target_id FROM {field_data_field_account} fa WHERE fa.entity_id = :uid AND fa.bundle = :bundle", array(':uid' => $user->uid, ':bundle' => 'user'))->fetchField();
}
| improve this answer | |
0

You could achieve this by either one of the following:

By using db_query():

function custom_get_user_account_id() {
    global $user;
    return db_query('SELECT field_account_target_id FROM {field_data_field_account} WHERE entity_id = :user_id AND bundle = :bundle', [
        ':user_id' => $user->uid,
        ':bundle' => 'user',
    ])->fetchField();
}

Or by using db_select():

function custom_get_user_account_id() {
    global $user;
    return db_select('field_data_field_account', 'fa')
        ->fields('fa', ['field_account_target_id'])
        ->condition('entity_id', $user->uid)
        ->condition('bundle', 'user')
        ->execute()->fetchField();
}
| improve this answer | |

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.