Rob
Rob

Reputation: 305

PHP: PDO (mysql) using bindValue returns wrong result

The code I've got so far doest return what I need. I can't see what is going wrong here. With a 'bad' adjustment to the code it gives the right output but I think its better to do it correctly. And why doesn't it work?

wrong output: Array ( [L] => L )

right output: Array ( [L] => 9 )

this code give the wrong output:

public function getStockByID_SIZE($size, $stockId){
    try {

    $this->_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    $sth=$this->_dbh->prepare("SELECT :size from stock WHERE id_product = :stockId"); 
    $sth->bindValue(':size', $size, PDO::PARAM_STR);
    $sth->bindValue(":stockId", $stockId);

    $sth->execute();
    $result = $sth->fetch(PDO::FETCH_ASSOC);
    return $result;

    } catch (PDOException $e) {     
        return "Error";  
    }
}

Same code but with a (bad) adjustment returns the right code:

 $sth=$this->_dbh->prepare("SELECT $size from stock WHERE id_product = :stockId"); 

//compared to:

 $sth=$this->_dbh->prepare("SELECT :size from stock WHERE id_product = :stockId");
 $sth->bindValue(':size', $size); //use of PDO::PARAM_STR doenst matter for outcome

Upvotes: 0

Views: 415

Answers (1)

xdazz
xdazz

Reputation: 160983

$sth=$this->_dbh->prepare("SELECT L from stock WHERE id_product = :stockId"); is the right way.

Your way is just doing SELECT 'L' from stock WHERE id_product = :stockId which gives you the result 'L'.

You can just doing something like below after validate the $size,

$sth=$this->_dbh->prepare("SELECT $size from stock WHERE id_product = :stockId");

Upvotes: 2

Related Questions