0

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

1 Answer 1

2

$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");

Sign up to request clarification or add additional context in comments.

4 Comments

but L varies, I could use the $size but is that ok?. I'll adjust the op
@Rob What do you mean $size is validate?
that $size is validate before it enters the class function . Should it be as well in the class function itself?
@Rob Then you can use it in your sql.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.