2016-08-27 76 views
1

我用codeigniter中的sha2哈希函数编写了一个查询,但生成的查询没有正确生成。Codeigniter查询没有正确生成

这里是我的模型代码:

public function validate_user($data = NULL) 
{ 
    $email = $data["email"]; 
    $password = $data["password"]; 
    $this->db->select('user_id'); 
    $query = $this->db->get_where('users', array('sha2(username, NULL)' => $data["username"], 'password' => $password)); 
    return $query->row_array(); 
} 

而这里的我得到(由于格式不正确的查询)错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''FCD8FE02F495400DC020499AC31FC75ABA05005622FD7A2F01D37153724CB395' AND `password' at line 3 

SELECT `user_id` FROM `users` WHERE sha2(username, NULL) 'FCD8FE02F495400DC020499AC31FC75ABA05005622FD7A2F01D37153724CB395' AND `password` = '2668dcd9bac3c8bb60742f139876d1d6' 

为什么不来的=符号在sha2(username, NULL)'FCD8FE02F495400DC020499AC31FC75ABA05005622FD7A2F01D37153724CB395'之间

的实际查询的结果会是:

SELECT `user_id` FROM `users` WHERE sha2(username, NULL) = 'FCD8FE02F495400DC020499AC31FC75ABA05005622FD7A2F01D37153724CB395' AND `password` = '2668dcd9bac3c8bb60742f139876d1d6' 

而不是:

SELECT `user_id` FROM `users` WHERE sha2(username, NULL) 'FCD8FE02F495400DC020499AC31FC75ABA05005622FD7A2F01D37153724CB395' AND `password` = '2668dcd9bac3c8bb60742f139876d1d6' 

任何想法我做错了吗?

+0

用户名存储为普通用户名或sha2()值? – Tpojka

+0

第二个问题,我可以检查([这里](http://php.net/manual/en/function.hash.php)和[这里](http://php.net/manual/en/function)。 hash-algos.php))'sha1','sha224''sha256','sha384'和'sha512'哈希算法,但不包含'sha2'。 'sha2()'从哪里来? – Tpojka

+0

谢谢你的回复Tpojka。用户名在数据库中以纯文本格式存储,但我的客户端将发送用户名sha256,所以我想检查它的唯一方法是使用mysql的sha2函数(原因是我正在检查,我意识到sha256值的客户端发送和由mysql生成的sha2是相同的,给定一个特定的用户名) – mrid

回答

1

这实际上是一个简单的查询,使用Codeigniter方法来构建语句在这种情况下不起作用。

尝试使用像这样更简单的绑定查询。

$sql = "SELECT user_id FROM users WHERE sha2(username, 256) = ? AND `password` = ?"; 
$query = $this->db->query($sql, array($data["username"], $data["password"])); 
return $query->row_array(); 

注意我把第二个参数放到mysql sha2()调用中。我认为这两个参数都是必需的,如果其中一个丢失或为空,则sha2()返回null。