我正在关注此tutorial系列,以学习制作登录脚本。
我完成了整个教程,但我不断抛出这个错误。
I am using CodeIgniter Framework 2.02
这是我得到的错误:
A Database Error Occurred
Error Number: 1054
Unknown column 'anil' in 'where clause'
SELECT user_id FROM users WHERE username = anil AND password = password
Filename: D:\xampp\htdocs\c_login\system\database\DB_driver.php
Line Number: 330<
以下是我的模型中执行SQL的函数:
function check_login($username, $password)
{
$sha1_password = sha1($password);
// The Guy uses ' ? ' in the video for the below statement and it works
// I tried replacing ? with $username & $password, but it didnt work..
// When I use the ?, I think it does query the DB, but I get the error
// Incorrect Username or Password, Even though it is correct.
// I only have 1 record on my DB, db = c_login, table=users
// Fields are user_id username password email name
$query_str = "SELECT user_id FROM users WHERE username = ? AND password = ?";
$result = $this->db->query($query_str, $username, $sha1_password);
if($result->num_rows() == 1)
{
return $result->row[0]->user_id;
}
else
{
return false;
}
}
此外,如果需要,这是我的控制器中的登录功能..
public function login()
{
$this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[50]|xss_clean');
// If form_validation has NOT been run, load the view login form
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
}
else // Else process login
{
// Process input and login
$username = $this->input->post('username');
$password = $this->input->post('password');
$user_id = $this->User_model->check_login($username, $password);
if( ! $user_id)
{
// Login Failed Error
$this->session->set_flashdata('login_error', TRUE);
redirect('user/login');
}
else
{
// Log them in
$this->session->set_userdata(array(
'logged_in' => TRUE,
'user_id' => $user_id
));
redirect('user/main_page');
}
}
}
所以基本上,如果我在SQL查询中使用问号,它会一直说不正确的用户名或密码,但如果我用变量$ username&amp; $ password,我在第一个代码块中得到错误。错误号码:1054, 我究竟做错了什么?我可以发誓这么简单......
答案 0 :(得分:2)
此
SELECT user_id FROM users WHERE username = anil AND password = password
可能会使用'
:
SELECT user_id FROM users WHERE username = 'anil' AND password = 'password'
像这样,它被解析为字符串,而不是列名。
答案 1 :(得分:2)
尝试利用Active Record并执行以下操作(为了清晰起见,详细版本):
function check_login($username, $password)
{
$sha1_password = sha1($password);
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->where('password', $sha1_password);
$result = $this->db->get('users');
if($result->num_rows() == 1)
{
$row = $result->row();
return $row->user_id;
}
else
{
return false;
}
}
数据会自动转义,因此您无需担心。在控制器中,将此部分重写为:
if($user_id == FALSE)
{
$this->session->set_flashdata('login_error', TRUE);
redirect('user/login', 'refresh');
}
else
{
$this->session->set_userdata(array(
'logged_in' => TRUE,
'user_id' => $user_id
));
redirect('user/main_page', 'refresh');
}
答案 2 :(得分:1)
修复查询绑定:
$result = $this->db->query($query_str, array($username, $sha1_password));