2

I am new to CodeIgniter, but not new to PHP, and I was wondering what I needed to do in CodeIgniter in order to make all of my queries secure.

Usually, I just use mysql_real_escape_string() on each variable used in the query (standard PHP), but I watched a tutorial on CodeIgniter, where the author didn't escape the variable and just did a standard insert like the following:

$this->db->query("SELECT * FROM Users WHERE Username = ?", array($username));

Which way is correct?

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
max_
  • 24,076
  • 39
  • 122
  • 211

1 Answers1

5

Your example does parameter binding

As you can read in the last paragraph of the above link, binding automatically escapes the value passed to query:

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.

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
  • 2
    Please note that this method is infinitely safer than using mysql_real_escape_string, which is often used incorrectly or in an unsafe configuration, leading to sql-injectable code. You should never use mysql_real_escape_string unless bound parameters are unavailable. Get out of the habit of using it (and the regular mysql library) and look at the parameter binding in the mysqli or pdo libraries. http://stackoverflow.com/questions/110575/do-htmlspecialchars-and-mysql-real-escape-string-keep-my-php-code-safe-from-inje – Cheekysoft Nov 22 '11 at 09:54