...

View Full Version : Help with PHP PDO



ECoode
08-11-2012, 08:12 AM
Hey guys I just started to learn PHP PDO and I'm kinda lost with it.
Well practice makes perfect...

I'm trying to check is there row in the database with checking is there id..
There is form with text field for $Nickname
Code:


$SQL = "SELECT id FROM users WHERE nickname = '$Nickname'";
if( $STMT = $DBH->exec( $SQL ) == "1" ){
echo "OK";
}else{
echo "NO";
}


Even tough database has 'ECode' nickname field and I submit it;
always returns with 'NO'.
Thanks already for helping me :)

Nile
08-11-2012, 08:51 AM
The beauty of PDO is that you don't put raw variables into a query like that. PDO::exec will also not work with SELECT statements. Try this:


$query = $dbh->prepare("SELECT COUNT(id) FROM users WHERE nickname = ?");
$query->execute($nickname);

echo ($query->fetchColumn() == 1) ? "Ok" : "No";

ECoode
08-11-2012, 08:57 AM
The beauty of PDO is that you don't put raw variables into a query like that. PDO::exec will also not work with SELECT statements. Try this:


$query = $dbh->prepare("SELECT COUNT(id) FROM users WHERE nickname = ?");
$query->execute($nickname);

echo ($query->fetchColumn() == 1) ? "Ok" : "No";


I tried something like this too, but got error like now;


Warning: PDOStatement::execute() expects parameter 1 to be array, string given in [LINE]


EDIT: It works now when I edited the code to this:
$QUERY->execute(array( $Nickname ));
Thanks :P

Nile
08-11-2012, 09:00 AM
*embarrassed*

Change that line to:


$query->execute(array($nickname));



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum