views:

77

answers:

2

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.

+5  A: 

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?

ryanday
Thanks, that did exactly what I needed.
jonescb
+1  A: 

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.

Milen A. Radev