向PHP会话变量添加完整查询?

I've never thought of doing this before, and am unsure of the risks. It's a one time session for each page, replaced by the next page visited.

What's the security risk of doing something like the following? If any?

$_SESSION['somename'] = "SELECT `something` FROM `table` WHERE `something`='blah'";

Is this a safe method, if not, what's a safer method to store a one time query that will be replaced?

It's probably safer to store queries within a temp mysql table. But I want to avoid additional mysql calls.

It is not a safe way to set variable with PHP due to the potential of exposing table names that can potentially be DROPPED via SQL injection. Now, session variables are stored on the server and can not be accessed by the browser. However, why introduce a bad habit that could cause someone less savvy on your dev team to use that to set a cookie? Then you have a large problem that started out being benign. It is better to just place data in your PHP session variables that act as a user identifier.

It shouldn't be too harmful (see below), but it's bad practice.

DB queries are the data/model layer, session management is an entirely different topic. You would do yourself a huge favor in keeping those separate.

Also, if you need to cache something, you should cache results, not queries. You can, however, make sure that the result is tied to the user by adding an identifier to the result.

For example, you could store a DB query result in an array in Memcached, where the array key would be the user ID.

If you worry about performance of MySQL calls, you should look into normalization and proper indexing.

One note on potential harm: Session data are stored in the filesystem or (seldomly) in memory. On shared hosting systems, there may or may not be measures implemented that prevent other users from reading your session data. On the other hand, your PHP source code is also readable in clear text, and usually has the same permissions, so there's no additional attack vector. A real security threat would be introduced if others could write to your session data. But I hope that there are no such setups on the machines of serious hosting businesses.