12

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?

1
  • And what about in a SELECT query? How I can escape them? Commented Mar 23, 2018 at 3:29

2 Answers 2

26

It is unsafe not to use Query Binding. This will automatically escape all the values:

$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);"; 
$this->db->query($sql, [$data['lat'], $data['lng'], $data['date'], $data['type']]);
Sign up to request clarification or add additional context in comments.

2 Comments

You can make this even simpler: $this->db->query($sql, $data); This works for me! (I guess you shouldn't have any other keys in the data array for it to work)
Or rewrite it to Active Record Pattern: $this->db->inset('some_table', $data); much more straight forward and very easy. Just make sure that no auto-increment primary key field makes it into insert() method by using if (!isset($data['id'])) throw new { InvalidArgumentException('data[id] is not allowed for insert'); }
11

use $this->db->escape(); it will escape the string automatically

This function determines the data type so that it can escape only string data. It also automatically adds single quotes around the data so you don't have to:

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

Here is the reference Click Here

4 Comments

At the very end of the page, the section about parameter binding is a much better option ;)
$this->db->escape() adds the single quotes so we don't have to, yet in your query you have added them.(I don't know if its the version difference or what, I am using 3.1.*) Earlier today I was writing a query and then I faced a Problem where I had made this mistake.
The doc quoted text and the implemented snippet are contradictory. escape() adds quotations around values as needed, and yet the snippet is erroneously adding quotations manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.