简体   繁体   中英

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->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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM