SELECT * FROM insanity LIMIT ∞

This was just unearthed in an application someone else (who shall remain nameless) built just about two years ago.  It’s reformatted to fit here, but otherwise unchanged.

$result = mysql_query("SELECT * FROM table_name"
    . " WHERE  id >= '" . mysql_real_escape_string($_POST['id'])
    . "' ORDER BY  `id` ASC LIMIT 0 , 1");

if ( !($row = mysql_fetch_array($result, MYSQL_ASSOC)) ) {
    $result = mysql_query("SELECT * FROM table_name"
        . " WHERE  id >= '1'"
        . " ORDER BY  `id` ASC LIMIT 0 , 1");
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
}

So… we start by selecting all rows with id >= 27, then limit the results to only the first one… which should be id = 27.

Of course, if I ask for an id that’s not really in the database, I’ll now get some arbitrary other row that happens to be numbered next.  Plus, if we didn’t get any rows from the first query, we try again starting from ‘1’, thus returning whatever row we happen to find.

This is just awesome.