note 68221 added to function.mysql-real-escape-string

From: Date: Tue, 18 Jul 2006 20:19:48 +0000
Subject: note 68221 added to function.mysql-real-escape-string
Groups: php.notes 
Request: Send a blank email to php-notes+get-114898@lists.php.net to get a copy of this message
It seems to me that you could avoid many hassels by loading valid database values into an array at the beginning of the script, then instead of using user input to query the database directly, use it to query the array you've created. For example: <?php //you still have to query safely, so always use cleanup functions like eric256's $categories = sql_query("select catName from categories where pageID = ?",$_GET['pageID']); while ($cts = @mysql_fetch_row($categories)) { //making $cts both the name and the value of the array variable makes it easier to check for in the future. //obviously, this naming system wouldn't work for a multidimensional array $cat_ar[$cts[0]] = $cts[0]; } ... //user selects sorting criteria //this would be from a query string like '?cats[]=cha&cats[]=fah&cats[]=lah&cats[]=badValue...', etc. $cats = $_GET['cats']; //verify that values exist in database before building sorting query foreach($cats as $c) { if ($cat_ar[$c]) { //instead of in_array(); maybe I'm just lazy... (see above note) $cats1[] = "'".mysql_real_escape_string($c)."'"; } } $cats = $cats1; //$cats now contains the filtered and escaped values of the query string $cat_query = '&& (category_name = \''.implode(' || category_name = \'',$cats).'\')'; //build a sql query insert //$cat_query is now "&& (category_name = 'cha' || category_name = 'fah' || category_name = 'lah')" - badValue has been removed //since all values have already been verified and escaped, you can simply use them in a query //however, since $pageID hasn't been cleaned for this query, you still have to use your cleaning function $items = sql_query("SELECT * FROM items i, categories c WHERE i.catID = c.catID && pageID = ? $cat_query", $pageID); ---- Server IP: 64.71.164.2 Probable Submitter: 24.218.17.59 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-real-escape-string.php Edit -- http://master.php.net/note/edit/68221 Del: integrated -- http://master.php.net/note/delete/68221/integrated Del: useless -- http://master.php.net/note/delete/68221/useless Del: bad code -- http://master.php.net/note/delete/68221/bad+code Del: spam -- http://master.php.net/note/delete/68221/spam Del: non-english -- http://master.php.net/note/delete/68221/non-english Del: in docs -- http://master.php.net/note/delete/68221/in+docs Del: other reasons-- http://master.php.net/note/delete/68221 Reject -- http://master.php.net/note/reject/68221 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#114898) next »