17

I have the following code:

function dbPublish($status)
{
 global $dbcon, $dbtable;

 if(isset($_GET['itemId']))
 {
  $sqlQuery = 'UPDATE ' . $dbtable . ' SET active = ? WHERE id = ?';
  $stmt = $dbcon->prepare($sqlQuery);
  $stmt->bind_param('ii', $status, $_GET['itemId']);
  $stmt->execute();
  $stmt->close();
 }
}

Do I need to mysql_real_escape_string in this case or am i okay?

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Babak
  • 279
  • 1
  • 7
  • 16
  • 1
    Note that only parameters are immune to SQL injection; any variable interpolated directly into the query string (such as `$dbtable`) is a potential vector, if its value comes from user input. Of course, things like table and column names should never come directly from user input. – outis Feb 17 '10 at 21:03

3 Answers3

32

No, you don't have to escape value yourself (i.e. no you don't need to call mysqli_real_escape_string), when you are using prepared statements : the DB engine will do that itself.

(Actually, if you were calling mysql_real_escape_string and using bound parameters, your strings would get escaped twice -- which would not be great : you'd end up with escaping characters everywhere...)


As a sidenote : your values are passed as integers (as indicated by the 'ii'), so you wouldn't have to call mysql_real_escape_string, even if you were not using prepared statements : as its name indicates, this function is used to escape... strings.

For integers, I generally just use intval to make sure the data I inject into my SQL queries really are integers.

(But, as you are using prepared queries, once again, you don't have to do that kind of escaping yourself)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
1

No, you must not. Combining the two would result in visible escape characters showing up in your data.

nobody
  • 19,814
  • 17
  • 56
  • 77
0
function dbPublish($status)    
{    
 global $dbcon, $dbtable;    

 if(isset($_GET['itemId']))    
 {    
  $sqlQuery = 'UPDATE ' . $dbtable . ' SET active = ? WHERE id = ?';    
  $stmt = $dbcon->prepare($sqlQuery);    
  $stmt->bind_param('ii', $status, $_GET['itemId']);    
  $stmt->execute();    
  $stmt->close();    
 }    
}   
ksihro
  • 1