Below is the code I use in my Codeigniter
project for logging in an admin user
public function login()
{
$usename = $this->input->post('username');
$password = $this->input->post('password');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get('user');
if($query->num_rows() == 1)
return true; // login the user
else
return false; // user not found
}
When the query is echoed
echo $this->db->last_query();
it outputs something like this:
SELECT * FROM (`user`) WHERE `username` = 'admin'
AND `password` = '5f4dcc3b5aa765d61d8327deb882cf99' LIMIT 1
Now when I input the password as value)'; DROP TABLE user;--
, the query produced is :-
SELECT * FROM (`user`) WHERE `username` = 'admin'
AND `password` = 'c0b24ab68e0f79e23ebec36e36a5309f' LIMIT 1
So I guess it is pretty much safe from sql injection
because codeigniter
active record
is automatically escaping the input data.
Edit based on comment
Now username is input with something like this
username'; DROP TABLE user;--
then, the query produced isSELECT * FROM (`user`) WHERE `username` = 'username\'; DROP TABLE user;--' AND `password` = '5f4dcc3b5aa765d61d8327deb882cf99' LIMIT 1
So I guess it is escaping in that case also.
But my question is, whether the above code is really sufficient enough to prevent all the possible sql injection attacks?