2

It never works. And when I do a var dump on the sql query I see that the question marks are still in it. Which means that the values have not been binded right?

I don't understand why it's not binding the values.

Can anybody help me out?

PHP

$ruleValue = "value1";
$input = "value2";
$inputValue = "value3";

$this->_db->query('SELECT * FROM ? WHERE ? = ?', array($ruleValue, $input, $inputValue));

Method

public function query($sql, $params = array()) {
    $this->_error = false;

    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
        var_dump($this->_query);
    }

    return $this;
}

var_dump

object(PDOStatement)#5 (1) { ["queryString"]=> string(27) "SELECT * FROM ? WHERE ? = ?" }
Kid Diamond
  • 2,232
  • 8
  • 37
  • 79
  • 3
    You cannot bind table names and column names. Further on this: http://stackoverflow.com/questions/15182910/php-pdo-bind-table-name – vee Apr 21 '14 at 16:04
  • @vee `=` in this `if($this->_query = $this->_pdo->prepare($sql))` really mean something in `if` statement? – Stranger Sep 15 '17 at 15:05
  • 1
    @Stranger, the `=` in `if` statement to me is OP's desire to reduce one line of code, but it's valid. `_pdo->prepare()` if successful returns `PDOStatement` and `false` otherwise. It might also raise `PDOException`. Use of assignment `=` vs equality `==` is your confusion, is my assumption correct? Use of `try...catch` around `prepare` and checking for `if (!$this->query)` might have been more readable? – vee Sep 15 '17 at 15:48
  • @vee Yeah, thanks for the clarification – Stranger Sep 15 '17 at 15:58

1 Answers1

5

Your code:

$ruleValue = "value1";
$input = "value2";
$inputValue = "value3";

$this->_db->query('SELECT * FROM ? WHERE ? = ?', array($ruleValue, $input, $inputValue)

4 lines
insecure
saves state -> a HUGE pitfall you dug for yourself
never works

regular PDO

$stmt = $this->db->prepare('SELECT * FROM value1 WHERE value2 = ?')
$stmt->execute([$value3]);
$results = $stmt->fetchAll();

3 lines
secure
stateless works

Conclusion: GET RID of this malicious function and use raw PDO

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • U say it's malicious, but how is it malicious exactly? – Kid Diamond Apr 21 '14 at 18:12
  • 1
    1. As I said above, introducing state, you'll be in trouble as soon as you try a nested query. Class variable $stmt will be overwritten and your code screwed up. 2. Having table and field names as variables is a call for disaster. – Your Common Sense Apr 23 '14 at 09:20