Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query escaping + codeigniter

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:

  • PHP error message: Undefined variable: user_language
  • SQL error: syntax wrong...near 'VALUES(NULL)' at line 1
like image 673
chowwy Avatar asked May 03 '12 16:05

chowwy


People also ask

Does CodeIgniter prevent SQL injection?

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.

How do you escape special characters in CodeIgniter?

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.

How do you check query is executed or not in CodeIgniter?

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.


1 Answers

$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.

like image 178
Hajo Avatar answered Sep 30 '22 16:09

Hajo