Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.

The query is like this:

$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);

The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.

I know I could probably just do this query:

"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
    //...
}

But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.

share|improve this question
up vote 6 down vote accepted

You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?

$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];

Is that what you are looking for?

share|improve this answer
    
Thanks, that did exactly what I needed. – jonescb Dec 3 '09 at 20:38

Use pg_fetch_result:

$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);

But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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