why this doesn’t work:
public function query($query, $vars = array())
{
$link = $this->getLink();
if($link)
{
$stmt = $link->prepare($query);
if($stmt)
{
if(count($vars)>0)
{
$count = 1;
foreach($vars as $v)
{
$stmt->bindParam($count, $v);
$count++;
}
}
if($stmt->execute())
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
return false;
}
and this works:
public function query($query, $vars = array())
{
$link = $this->getLink();
if($link)
{
$stmt = $link->prepare($query);
if($stmt)
{
if($stmt->execute($vars))
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
return false;
}
calling:
$result = $db->query('select * from users where user like ? and email like ?',array('my_user', 'myemail@domain.com'));
edit with final code:
public function query($query, $vars = array())
{
$link = $this->getLink();
if($link)
{
$stmt = $link->prepare($query);
if($stmt)
{
if(count($vars)>0)
{
$count = 1;
foreach($vars as $v)
{
$stmt->bindValue($count, $v);
$count++;
}
}
if($stmt->execute())
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
return false;
}
The reason is that
bindParambinds a variable (not its value) to a parameter. However,$v‘s value changes with each iteration of theforloop therefore each of your query’s parameters would have the last item in the array as their value (not what you want I’m sure).I would suggest using
bindValueinstead ofbindParam