PHP sessions in MySql queries is it safe?

Hi there, i have been developing a system which makes extensive use of the global session variable containing the username of the authenticated user within my mysql SELECT statements.

I was just wondering about the security implications of this. Recently i have seen a new trend pop up where PHP provides ‘prepare’, ‘bind values’ and ‘execute’ statements are used to prevent mysql injection.

I was just wondering if i should go nuts with this new style of implementation or can i just leave it as-is?

If you think it is worth it, can you point me in the direction of some tutorials because i cant seem to find the search engine buzz word for it.


You didn’t show us any code so it’s hard to say whether you can leave it as it is. If you properly escape all values you put into sql queries then you can leave it as it is. By proper escaping I mean:

  1. Using mysql_real_escape_string or mysqli_real_escape_string for string values
  2. Sanitizing numeric values, for example with (int), (float), etc.
  3. To be 100% safe, use mysql(i)_set_charset after connecting to the database as there are reports of incorrect escaping with certain (rarely used) character sets if they are not set properly after connecting.

Alternatively you can use prepared statements, there was a thread about it:

Personally, I’m not so keen of using prepared statements for escaping strings because I don’t think this is their purpose - rather a side effect. But many people like this style, just check out PDO and decide for yourself.