Welcome Guest, Not a member yet? Register   Sign In
Escape string before inserting in a query
#1

(This post was last modified: 06-06-2018, 08:13 AM by glorsh66.)

I  know that when you are using CI query builder you don't need care about it, because CI automatically escapes strings for you.

But what if i need to use my own SQL query (which is not possible to build using query builder, or it's possible but only by taking really convoluted and strage ways)

for instance (it can be much more complicated, it is just an example) 

Code:
$query = $this->db->query("SELECT * FROM `PM_board` WHERE `lesser_id` ={$owner}
UNION
SELECT * FROM `PM_board` WHERE `greater_id` = {$owner}");
I am using this query for Index optimization, because a built in mysql operator OR don't properly use indexes.


How do I protect myself from MySQL injection in this case?
What function do I need to use on $owner to escape all dangerous symbols.
But I don't want to distort string representation. I don't want to change HTML entities, only to escape string.
Reply
#2

MySQL Documentation - Table 9.1 Special Character Escape Sequences
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

$this->db->escape() Will be enough?
Reply
#4

Or Do I need to do something else to close all possible holes for a SQL injection attack?
Reply
#5

You can use that one or query binding.
I find it easier to use the latter.

PHP Code:
$query $this->db->query("SELECT * FROM `PM_board` WHERE `lesser_id` = ?
UNION
SELECT * FROM `PM_board` WHERE `greater_id` = ?"
,array($owner,$owner)); 
Reply
#6

(This post was last modified: 06-07-2018, 03:25 PM by php_rocs.)

I too prefer query binding too because as the CI documentation says... 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.



@glorsh66, I've been able to write some pretty complex queries using the CI query builder...for example


PHP Code:
public function Complex_query($userid)
{
$year date("Y");

// complex query
$qry "select * from Table1 t1
       LEFT OUTER JOIN (
       Select * from Table2 where userid = ? and year = ?) t2 ON t1.fk = t2.id
       UNION
       Select * FROM Table1 t1
       RIGHT OUTER JOIN Table2 t2 ON t1.fk = t2.id;"
;

// array of variables in order
$var = [$userid,$year];

// query builder with binding
$query $this->CI->db->query($qry,$var);


return (
$query->num_rows() > 0) ? $query->result_array() : FALSE;

Reply
#7

Thanks!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB