Jump to content


Photo

PDO in PHP help


  • Please log in to reply
1 reply to this topic

#1 Vic Vance

Vic Vance

    Young Padawan

  • Members
  • Pip
  • 21 posts

Posted 16 March 2012 - 10:10 AM

I am learning PDO SQL statements. I have got a slight problem, I do not know how to convert the following mysql statement into PDO statement.

$_SESSION['id']			= ( isset( $_SESSION['id'] ) ) ? $_SESSION['id'] : FALSE;
$_SESSION['password']	= ( isset( $_SESSION['password'] ) ) ? $_SESSION['password'] : FALSE;

$logged = mysql_query("SELECT * FROM `db_members` WHERE `id`='".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'");
$logged = mysql_fetch_array( $logged );

I tried solving the problem and the following works:

$_SESSION['id']			= ( isset( $_SESSION['id'] ) ) ? $_SESSION['id'] : FALSE;
$_SESSION['password']	= ( isset( $_SESSION['password'] ) ) ? $_SESSION['password'] : FALSE;

$sth = $dbh->query('SELECT * FROM `db_members` WHERE `id` = '.$_SESSION['id'].'');
$sth->execute();
		
$logged = $sth->fetch(PDO::FETCH_OBJ);
		
echo $logged ->id;

The problem is the code stops working, when I add the following:

AND `password` = '.$_SESSION['password'].'

I am not sure why is this happening.. are there restrictions for using AND in PDO? I looked online and there is hardly any help in this case. Please help, I really want to know whats the problem.. thanks

Edited by Vic Vance, 16 March 2012 - 10:11 AM.


#2 Hayden

Hayden

    P2L Jedi

  • Members
  • PipPipPip
  • 717 posts
  • Gender:Male
  • Location:Texas

Posted 18 March 2012 - 06:21 PM

First of all, I would not pass the user password via sessions. It's not very secure, better to accept it immediately from a form post as an option.

Also, avoid using "SELECT *" and instead specify the columns you need.

<?php

$db = new PDO('mysql:dbname=yourDBname');


$sql = "SELECT id FROM `db_members` WHERE `id`=:user_id AND `password` = :password LIMIT 0,1";
$query = $db->prepare($sql);

// bindParam injects the values you want in the names variables in the query
$query->bindParam( ":user_id", $_SESSION['id'] );
$query->bindParam( ":password", $_SESSION['password'] );

$query->execute();

if( $query->rowCount() > 0 )
{
	// Success!

	// Get the row that was found
	$user = $query->fetchObject();

	// Column `id`
	$loggedInUser = $user->id;

} // end if

Edited by Hayden, 18 March 2012 - 06:55 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users