SELECT with $_SESSION['uid'] using PDO

Hi I am trying to SELECT id from user WHERE $_SESSION[‘uid’] using PDO. I got a
Catchable fatal error: Object of class PDOStatement could not be converted to string. I have a feeling I am setting it wrong, can someone please show me the proper format? Thanks in advance.

[php]$sessionid = $_SESSION[‘uid’];

$id = $conn->prepare(“SELECT id FROM user WHERE id = :sessionid”);
$id ->bindParam(’:sessionid’, $sessionid, PDO::PARAM_INT);
$id->execute();

[/php]

Looks fine to me, not sure if you can have a space between the $id and -> [php]$id ->bindParam[/php]

Hi, I adjusted the space and still got a Catchable fatal error: Object of class PDOStatement could not be converted to string. Thanks for the response.

Honestly this whole thing could be much simpler. Are you sure that $_SESSION[‘uid’] actually has a value? Try echoing it before the query to make sure it has the value you expect.
[php]
$id = $conn->query("SELECT id FROM user WHERE id = ". (int)$_SESSION[‘uid’]);
[/php]
If that still fails then you need to echo out the query error and see what went wrong with the query.
[php]print_r($conn->errorInfo());[/php]

Hi. Yes, I did originally have it that way and it works. I seen examples of PDO SELECT using prepared statements, so I was trying to do it with a prepared statement. Is it necessary to use prepared statement when using SELECT?

There are many times when prepared statements are needed, but in the instance you have it’s not needed cause you are able to explicitly declare the variable to an int which can then only be an int which is able to create a sql injection. In short, it all depends on what you are doing that decides if you need a prepared statement.

That makes sense sense since the UID is an int. It’s just so bizzare that it I am able to get the $_SESSION[‘uid’] when I used $conn->query but it doesn’t work when I used $conn->prepare. I echo the $_SESSION[‘uid’] on the bottom of the page and it shows the uid value, so I know it isn’t a db connection problem. I also can get $conn->prepare to SELECT all the other columns except for the uid. Thanks for the input.

Just think on about using the users ID as the session ID. Not very secure when it comes to session hijacking. You’d be a little more secure encrypting the UserID using a unique SALT key which would be unique to the user. I tend to generate a SALT key on user signup using datetime that way each user has a unique key generated using as little resources as possible. Still not 100% secure though but then nothing is!

Sponsor our Newsletter | Privacy Policy | Terms of Service