Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO - bindParam not working

Tags:

php

mysql

pdo

I'm creating a PDO class to use on my projects, but since I'm new to it I'm not being able to bind parameters to a prepared sql statement, with not error whatsoever. Here's the function that is ment to do it :

# ::bindParam
public static function bind()
{
    # get function arguments
    $args = func_get_args();

    # check for any arguments passed
    if (count($args) < 1)
    {
        return false;
    }

    foreach ($args as $params)
    {
        # named variables for convenience
        $parameter = $params[0];
        $variable = $params[1];
        $data_type = isset($params[2]) ? $params[2] : PDO::PARAM_STR;
        $length = isset($params[3]) ? $params[3] : null;

        # bind param to query
        Database::$statement->bindParam($parameter, $variable, $data_type, $length) or die('error');
    }
}

and a prepared sql statement :

SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1

Can someone point me in the right direction? The query produces no errors at this point. Note that I am assuming the problem is here, although it might not, since I'm only using bindParam() and prepare().

edit - trigger code

    $email = $_POST['email'];
    $password = $_POST['password'];

    $password = hash('sha256', $password);

    $this->db->prepare('SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1');
    $this->db->bind(
        array(':email', $email),
        array(':password', $password)
    );
    $status = $this->db->execute();

    if ($status)
    {
        $result = $this->db->fetch('assoc');

        $this->template->user = $result;
    }
    else
    {
        $this->template->user = false;
    }
like image 332
yoda Avatar asked Dec 12 '22 15:12

yoda


1 Answers

As @YourCommonSense already mentioned, raw PDO interface is a little bit clearer, however the problem is probably due to the use of function PDOStatement::bindParam() instead of PDOStatement::bindValue().

The difference between those two is that, the first one takes a variable reference, which is constantly overwritten in your foreach loop, while the last one takes the actual value of the variable.


If you're looking for some more friendly database connection interface, why won't you try Doctrine DBAL?

like image 112
Crozin Avatar answered Dec 28 '22 09:12

Crozin