ZiTAL
ZiTAL

Reputation: 3581

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', '[email protected]'));

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

Upvotes: 0

Views: 1248

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157863

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

Upvotes: 1

Tarek Fadel
Tarek Fadel

Reputation: 1959

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

Upvotes: 2

Related Questions