5

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.

2 Answers 2

8

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.