tags:

views:

643

answers:

3

I'm trying to stuff a variable into a SQL query to return a value to a page.

$sql = 'SELECT account FROM users WHERE uid = arg(1)';

Where arg(1) = the user currently being viewed. I am outputting arg(1) at the top of the page, so I know it's there, but Drupal doesn't seem to want to take it. I've tried escaping several different ways. Below is the full code

  function accountselect_getclientaccount() {
      global $user;
      $sql = 'SELECT account FROM users WHERE uid = arg(1)';
      $result = db_result(db_query($sql));
    return $result;
  }
+1  A: 

You could try:

$uid = arg(1);
$result = db_result(db_query("SELECT account FROM {users} WHERE uid = %d", $uid));
anonymouse
You're the man(or the woman)! :)
cinqoTimo
+1  A: 

To avoid sql-injection, you should use placeholders (see db_query for more info):

$result = db_query("SELECT * FROM {users} WHERE uid = %d", arg(1));

Also note that db_result is meant for single-column, single-result queries. You probably want to use db_fetch_object. Additionally, there isn't a column in the users table called account.

jhedstrom
Thanks, jhedstrom - isn't the solution provided by anonymouse the same in terms of SQL injection attacks...?By the way, I am only trying to grab one value, and I have created a column named `account`. I know that's like pissing on the Drupal bible, but for the specific situation I wanted to use it for, it needed to go that way. Besides, I'm betting that the User table doesn't change that much...
cinqoTimo
It is the same as anonymouse's...I think we cross-posted those answers.
jhedstrom
+1  A: 
function accountselect_getclientaccount() {
  return (arg(0) == 'user') ? db_result(db_query('SELECT account FROM {users} WHERE uid = %d', arg(1))) : FALSE;
  }

I don't know why you're using the global $user. Maybe you should be using $user->uid instead of arg(1)? This would save you checking arg(1) is actually a user ID.

This might be better:

function accountselect_getclientaccount($account) {
  return db_result(db_query('SELECT account FROM {users} WHERE uid = %d', $account->uid));
  }

Also: see the user hook. It might be best practice to return the 'account' col on the load operation (if you're not doing that already)

http://api.drupal.org/api/function/hook_user/6

Rimian
You're right, I didn't need global $user in the code. I removed it shortly after. As far as the $user->uid, that returns the uid of the currently logged in user. arg(1) returns the uid of the user whose account you are viewing. The purpose of the function is to load the users current account as default value in the select list. It was sort of a pain. What is 'load' operation? A user-edit state?
cinqoTimo
Rimian