Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I prefer to do whitelisting and treat the http parameter string as separate from the string that gets interpolated into the SQL query. </p> <p>In the following PHP example, the array keys would be the values passed in as http parameters, some kind of symbolic label for different ordering schemes, according to your web interface. The array values would be what we want to interpolate into SQL for these corresponding ordering schemes, e.g. column names or expressions.</p> <pre><code>&lt;?php $orderby_whitelist = array( "name" =&gt; "last_name, first_name", "date" =&gt; "date_created", "daterev" =&gt; "date_created DESC", "DEFAULT" =&gt; "id" ); $order = isset($_GET["order"]) ? $_GET["order"] : "DEFAULT"; $order_expr = array_key_exists($order, $orderby_whitelist) ? $orderby_whitelist[$order] : $orderby_whitelist["DEFAULT"]; mysql_query("SELECT ... FROM ... ORDER BY $order_expr") </code></pre> <p>This has advantages:</p> <ul> <li><p>You can defend against SQL injection even for cases where you can't use query parameters. If the client passes an unrecognized value, your code ignores it and uses a default order.</p></li> <li><p>You don't have to sanitize anything, because the keys and values in the array are both written by you, the programmer. Client input can only pick one of the choices you allow.</p></li> <li><p>Your web interface does not reveal your database structure.</p></li> <li><p>You can make custom orders that correspond to SQL expressions or alternative ASC/DESC, as I showed above.</p></li> <li><p>You can change database structure without changing your web interface, or vice versa.</p></li> </ul> <p>I cover this solution in my presentation, <a href="http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies" rel="nofollow">SQL Injection Myths &amp; Fallacies</a>, and also in my book, <a href="http://www.pragprog.com/titles/bksqla/sql-antipatterns" rel="nofollow">SQL Antipatterns: Avoiding the Pitfalls of Database Programming</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload