Tom
Tom

Reputation: 12998

Placing a $_SESSION into a mySQL query

I have a query which runs fine if I manually declare $add to be a value (30 for example) by when I try to set it to the user_id session the query fails.

// $add = 30;
// The line above works
$add = mysql_real_escape_string($_SESSION['user_id']);
$query = "UPDATE mytable SET act=0, add=$add WHERE id=$selected_user";

Any ideas where I'm going wrong.

Upvotes: 0

Views: 111

Answers (3)

Ryan Brodie
Ryan Brodie

Reputation: 6620

I can almost guarantee that you've forgotten session_start(); at the top of your script. If not try echoing the session variable, if nothing is returned, you haven't set anything to it.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121881

Q: Any ideas where I'm going wrong?

A: Yes. Session is empty.

SUGGESTIONS:

  1. Do an "echo" to verify that $_SESSION['user_id'] is empty (I'm 99% sure it will be)

  2. Make sure you're actually setting a session (e.g. "session_start()")

  3. Make sure your "session_start()" occurs before your <html> tag.

  4. Debug the code that sets $_SESSION['user_id']

This is a good link:

http://www.w3schools.com/php/php_sessions.asp

Upvotes: 1

Oscar Jara
Oscar Jara

Reputation: 14187

When using sessions you always need to specify this before any $_SESSION usage like this:

session_start();
//now you are able to use this
$_SESSION['user_id'] = 30;

By the other hand, I got the same problem as you before and what you need to do is to put the $_SESSION['user_id'] in a variable, then you will be able to pass it to the mysql_real_escape_string without problems.

$id = $_SESSION['user_id'];
//now use this:
$add = mysql_real_escape_string($id);

Hope this helps.

Upvotes: 1

Related Questions