0

Say I have an array of key-value pairs with non-numerical keys. If I am going to be using those keys as values in an SQL INSERT statement, is it important to sanitize them as well?

Something like:

$food = array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat');
foreach($food as $foodType => $nameOfFood)
{
    $nameOfFood = stripslashes($nameOfFood);
    $foodType = stripslashes($foodType); //Is this necessary?
    $query = "INSERT INTO Foods(FoodType, NameOfFood) VALUES ($foodType, $nameOfFood)";
    // Execute query
}

If the $food array was populated through a POST statement, would sanitizing the keys be a concern?

  • 1
    If the keys are user generated, they yes. The basic rule is ***Never*** *trust user input*. – Script47 Jan 11 '16 at 21:10
  • 1
    if it's user input, yes; sanitize. Btw, that looks like pseudo code here. Those values are strings and require them to be quoted. – Funk Forty Niner Jan 11 '16 at 21:10
  • 1
    Yes and no. If you set it, then you don't need to input. But you also need to think of script injection. I'd suggest using PDO or mysqli, with binding so that you don't have the worry about doing it yourself. – aynber Jan 11 '16 at 21:11
  • `stripslashes()` doesn't safeguard against an SQL injection, a prepared statement does. – Funk Forty Niner Jan 11 '16 at 21:15

0 Answers0