简体   繁体   中英

PHP get result string from PostgreSQL Query

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM