user1482015
user1482015

Reputation:

when should I escape the sql query

Referring to CodeIgniter Query Builder.

There are many functions that accept an optional $escape parameter, defined as:

$escape (bool) – Whether to escape values and identifiers

In what situation should or should not escape?

Upvotes: 1

Views: 259

Answers (1)

mertyildiran
mertyildiran

Reputation: 6613

It's actually explained in the link that you have provided:

If you are using a database that CodeIgniter escapes queries for, you can prevent escaping content by passing an optional third argument, and setting it to FALSE.

It means; for example MySQL is supported and it will escape:

$this->db->having('user_id',  45);  // Produces: HAVING `user_id` = 45 in some databases such as MySQL

for disabling it:

$this->db->having('user_id',  45, FALSE);  // Produces: HAVING user_id = 45

But your question was when to use FALSE argument right? So let me give you a scenario for usage of FALSE argument from the old documentation:

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); 

This (FALSE) is useful if you need a compound select statement.

Without FALSE it will produce:

SELECT `(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4`

but with FALSE:

SELECT (SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4

and the desired case is the last one. Using FALSE is simply removes backticks (`).

This kind of usages is preferred because it's practical to write but I do not recommend it because it's confusing.

I prefer to write like this:

<?php
    .
    .
    $whatever_query = $this->db->get_compiled_select();
    $query = $this->db->query('SELECT (SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4 '.$whatever_query);
?>

But there are people prefer to use: $this->db->select() and this is why there is a FALSE argument.

By the way it's not a $this->db->select() specific issue. There could be many cases need to use FALSE argument when calling other query builder functions. But the common keyword of such cases is probably compound statement.

Upvotes: 3

Related Questions