问题描述
我正在创建要在我的项目上使用的PDO类,但是由于它是我的新手,所以我无法将参数绑定到准备好的sql语句上,而不会出现任何错误.这是执行此操作的功能:
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');
}
}
和准备好的sql语句:
and a prepared sql statement :
SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1
有人可以指出我正确的方向吗?此时查询不会产生任何错误.请注意,我假设问题出在这里,尽管可能没有,因为我只使用bindParam()和prepare().
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().
修改-触发代码
$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;
}
推荐答案
正如@YourCommonSense所述,原始PDO接口更加清晰,但是问题可能是由于使用了功能 PDOStatement::bindParam()
而不是 PDOStatement::bindValue()
.
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()
.
这两者之间的区别在于,第一个使用变量引用,它会在您的foreach
循环中不断被覆盖,而最后一个则取变量的实际值.
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.
如果您正在寻找更友好的数据库连接界面,为什么不尝试 Docal DBAL ?
If you're looking for some more friendly database connection interface, why won't you try Doctrine DBAL?
这篇关于PDO-bindParam不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!