Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quotes around int values in mysql queries

Tags:

php

mysql

I've gotten a habit of filtering the user submitted variable through my int function which makes sure it's a number (if not returns 0) and not quoting the variable in mysql queries.

Is that bad practice? I think I decided to do this for performance reasons. Plus I've always thought that numbers shouldn't be put in quotes.

Example:

if($perpage != $user['perpage']){
if($perpage == 50 || $perpage == 100 || $perpage == 200 ){
$DB->query("UPDATE users SET perpage=$perpage WHERE id=$user[id]", __FILE__, __LINE__);
}
}
like image 269
domino Avatar asked Nov 05 '11 18:11

domino


1 Answers

aha! an interesting case here!

  1. You are right in general. It is always better to treat numbers as numbers, not strings

    • it makes your code more sane and consistent
    • an strict_mode setting in mysql, which won't allow you do disguise a number as a string, if turned on.
  2. But your implementation in fact allows an injection! Let's leave it for your homework to find it :)

Here is a reference for you, explaining this injection: http://php.net/language.types.type-juggling

so, I'd make your code like this

$perpage = intval($perpage);
if($perpage != $user['perpage'] && in_array($perpage,array(50,100,200) { 
  $DB->query("UPDATE users SET perpage=$perpage WHERE id=$user[id]"); 
} 
like image 166
Your Common Sense Avatar answered Sep 21 '22 12:09

Your Common Sense