Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping SQL queries in Codeigniter

I am inserting some data into a MySQL table using CodeIgniter. Because I am using INSERT IGNORE INTO and do not want to edit the active records class to enable this feature, I am generating the SQL query manually.

$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
                        VALUES ('" . $data['lat'] . "', '" . $data['lng'] . "', '" . $data['date'] . "', '" . $data['type'] . "')");

Problem: The query failed when the string in $data['type'] contained a single quote. How can I make it such that these characters that need to be escaped gets escaped automatically, like when using Active records?

like image 259
Nyxynyx Avatar asked Jun 10 '12 12:06

Nyxynyx


People also ask

How do you escape special characters in CodeIgniter?

For escaping HTML output, in most cases htmlspecialchars() is all you need, but you can use the xss_clean() function any time.

Does CodeIgniter prevent SQL injection?

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 to use query in CodeIgniter?

To submit a query, use the following function: $this->db->query('YOUR QUERY HERE'); The query() function returns a database result object when "read" type queries are run, which you can use to show your results. When "write" type queries are run it simply returns TRUE or FALSE depending on success or failure.

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

The update function returns a value: $result = $this->db->update('mytable', $data); Check that value for either being TRUE (success) or FALSE (failure). update runs query internally and then returns the return value of query (Ref):


1 Answers

Another way is to use Query Binding which automatically escapes all the values:

$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);"; 
$this->db->query($sql, array($data['lat'], $data['lng'], $data['date'], $data['type']));
like image 172
Yan Berk Avatar answered Oct 06 '22 00:10

Yan Berk