I'm using codeigniter and most of the time use active record for my queries (which automatically escapes them), but this query doesn't seem to fit neatly into it because of the variable. So I need to figure out how to escape the query manually.
Codeigniter docs suggest escaping the queries this way:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
My original query
$sql = "SELECT * FROM (`user_language`) WHERE `user_id` = '{$id}'";
My escaped query
$sql = "SELECT * FROM (`user_language`) WHERE `user_id` = '{$id}' VALUES(".$this->db->escape($user_language).")";
But I'm having trouble getting the syntax right. Error messages are:
SQL Injection Prevention SQL injection is an attack made on database query. In PHP, we are use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this.
HTML output: You need to escape HTML output yourself with htmlspecialchars() or use CI's html_escape() function (as of 2.1. 0). This is not done automatically because there's no way to know the context in which you are using the data. xss_clean() - If you know what you're doing, you shouldn't need it.
We can get last executed query using last_query() function of db class in codeigniter. It is a very simple to use $this->db->last_query() function to see SQL statements of last executed query in php codeigniter app. You have to simple code that function after your main query that you wanted check.
$sql = "SELECT * FROM `user_language` WHERE `user_id` = " . $this->db->escape($id);
if you want to select the language of the user given by $id it should work that way.
dealing with numbers an alternative would be:
$sql = "SELECT * FROM `user_language` WHERE `user_id` = " . (int)$id;
codeigniter does also support prepared statements as "query bindings":
The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With