PHP PDO Not Binding Values

GarettM

Posting Freak
Aug 5, 2010
833
136
Hey i am trying to bind values to a query, when i manually "bind" it works just fine but when i try to do it another way "Way #2" it doesn't work :(
Manual Query Function
PHP:
public function query($sql, $params = array())
{
   $this->statement = $this->pdo->prepare($sql, $params);
   $this->statement->execute();
}

$this->result('SELECT value FROM cms_settings WHERE key=:key', array(':key' => 'url')); # returns http://localhost

Trying to clean it up but it doesn't work / Way #2
PHP:
public function query($sql, $params = array)
{
   $this->statement = $this->pdo->prepare($sql);

   foreach($params as $key => $value)
      $this->statement->bindValue(sprintf(':%s', $key), $this->quote($value));

   $this->statement->execute();
}

$this->result('SELECT value FROM cms_settings WHERE key=:key', array('key', 'url')); # returns false

Common Function
PHP:
public function result($sql, $params = array())
{
   $this->query($sql, $params);
   $result = $this->statement->fetch(PDO::FETCH_ASSOC);
   if(is_array($result))
      array_shift($result);
   return $result;
}

private function quote($value)
{
   return sprintf("'%s'", $value);
}
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,132
2,456
You don't include the type when you bind, the thirth parameter needs to be something like
Code:
PDO::PARAM_STR
Please read the PHP docs:
 

Users who are viewing this thread

Top