php pdo prepared statements: bindParam doesn't work
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->bind开发者_如何学GoParam($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 bindParam
binds a variable (not its value) to a parameter. However, $v
's value changes with each iteration of the for
loop 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 bindValue
instead of bindParam
I am not extremely familiar with PDO, but it seems you can't bind a variable which changes constantly. Use bindValue instead.
Also note that you should not use LIKE this way. Use =
instead
精彩评论