0

I've been trying to figure out how to bind values for a while but I cant seem to be getting the gist of it.

In this code block what I did is simply instantiate the '?' value that would be bind to another value. the output is something like this: INSERT INTO table1(column1, column2) VALUES(?, ?)

public function insertQuery($table, $fields = array()) {
        $keys = array_keys($fields);
        $values = '';
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';

            if($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO {$table} (`".implode('`,`', $keys)."`) VALUES({$values})";

        if($this->query($sql, $fields)) {
            return $this;
        }
        return false;
    }

everything works fine until the point where it reaches the execute() function of my query method

private function query($sql, $bind_value = array()) {
        if($this->_query = $this->_pdo->prepare($sql)) {
            if(count($bind_value)) {
                $x = 1;
                foreach($bind_value as $bind_values) {
                    echo "{$x} = {$bind_values} <br>";
                    $this->_query->bindValue($x, $bind_values);
                    $x++;
                }
            }
            if($this->_query->execute()) {
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            } else {
                echo 'a';
            }
        }
        return $this;
    }

it outputs a which means that the execute() was never run. Was there something I missed?

Marjo Forcado
  • 43
  • 1
  • 1
  • 4
  • When you (maybe only for debugging purposes) set the error mode to PDO::ERRMODE_EXCEPTION e.g.via `$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` prior to `if($this->_query = $this->_pdo->prepare....`, what is the actual error message you get? – VolkerK Mar 04 '16 at 07:35
  • why so complicated? check out smaller portions of your code instead of getting lost in this big clusterpiece. also it seems you never looked at the `PDO` documentation. `bindValue()` works in exactly two ways: `$stmt->bindValue(":parameter_name", $value)` or `$stmt->bindValue($parameter_number, $value)`. plus in your sql your parameters need too look like `:parameter_name` in the first case, or like `?` in the second case. – low_rents Mar 04 '16 at 07:39
  • Please note [The most fatal PDO code](https://phpdelusions.net/pdo/lame_update) – Your Common Sense Mar 04 '16 at 07:49
  • this is what your query method should be like: private function query($sql, $bind_value = array()) { $stmt = $this->_pdo->prepare($sql); $stmt->execute($bind_value); return $stmt; } – Your Common Sense Mar 04 '16 at 07:54

0 Answers0