co.ador Posted December 21, 2009 Share Posted December 21, 2009 I have a set up where the variable being escaped is an array and it needs to be iterated and escaped by separate. I need some help. <?php $arrFoodTypes = isset($_REQUEST['frmSearch']['food_types'])?mysql_real_escape_string($_REQUEST['frmSearch']['food_types']):array(); ?> How can I fit that if else statment inside the below foreach loop. the indexes has been a difficult to place them <?php foreach($_REQUEST as ['frmSearch]=>'['food_types']) {$data['frmSearch']=mysql_real_escape_string(['food_types]);} ?> Is this correctly syntaxed it? if any syntax error or mistake please correct me. Is iteration possible with the above set up at the foreach loop? Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/ Share on other sites More sharing options...
trq Posted December 21, 2009 Share Posted December 21, 2009 Your code is all over the place and without a decent description, hard to give you a better example. Is $_REQUEST['frmSearch']['food_types'] ? an array? If so, your code would be.... $data = array(); foreach ($_REQUEST['frmSearch']['food_types'] as $foodtypes) { $data[] = mysql_real_escape_string($foodtypes); } Assuming that is what your actually trying to do. Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981343 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 Sorry my thinking is confused, I thought that ['frmSearch'] was the key and ['food_types'] the value. In this case what ['frmSearch']['food_types'] are keys? How do they work as keys both in this case? Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981345 Share on other sites More sharing options...
trq Posted December 21, 2009 Share Posted December 21, 2009 Arrays can be multidimensional. eg: arrays within arrays. The example you posted looked like you are working with a multidimensional array, but obviously you are not. This is where YOU need to describe what the array you are working with actually looks like. print_r can help you if you would like to show us the contents of the $_REQUEST array. Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981347 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 that would be echo "<pre>"; print_r($arrFoodTypes); echo "</pre>"; ?> to see the array print right?. Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981359 Share on other sites More sharing options...
trq Posted December 21, 2009 Share Posted December 21, 2009 We need to see ther $_REQUEST array. echo "<pre>"; print_r($_REQUEST); echo "</pre>"; Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981361 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 This is the array print Array ( [frmSearch] => Array ( [name] => [zipcode] => 10468 [state] => NY [food_types] => Array ( [0] => ) [submit] => Submit ) ) Notice that the offerings index is not inside the print_r indexes that's the notice and warning below, That might be coming from the form name. Don't know cause the form name is identical to the index at the iteration, don't know why throwing those warning and notices below.. Notice: Undefined index: offerings in C:\wamp\www\nyhungry\indexpagination.php on line 16 Warning: Invalid argument supplied for foreach() in C:\wamp\www\nyhungry\indexpagination.php on line 16 Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981366 Share on other sites More sharing options...
trq Posted December 21, 2009 Share Posted December 21, 2009 Alright, so the code I posted in my first reply was correct and will loop through the $_REQUEST['frmSearch']['food_types'] array, escaping data and save it within an array called $data. If that isn't what you want you might want to actually describe what it is you do want. Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981369 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 it means the data of each index would be escaped or just the food_types index data? Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981372 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 someone has suggested me to iterate through so the notice below stop from happening <b>Warning</b>: mysql_real_escape_string() expects parameter 1 to be string, array given in <b>C:\wamp\www\nyhungry\indexpagination.php</b> on line <b>12</b><br The original problem was that a query apart from this extraction from the url display the content for an html frame based on the values extracted from the url variables coming from a form in page.1 After the display from the query i have to scape some of the results rows becuase they had apostrophe's preventing the INSERT query to put it in the database. I have sucessfully escaped the string with addslashes or stripslahes functions but still the query would not INSERT the string. why if the data is already escaped. The only thing display in the windows that could indicate a possible suggestion to the issue was that notice above. which as you and other people has suggested requires a iteration as we have done. help... on how could I sucessfully INSERT the string to the database Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981392 Share on other sites More sharing options...
trq Posted December 21, 2009 Share Posted December 21, 2009 That error indicates that you are trying to pass an array to mysql_real_escape_string. As the name suggests, mysql_escape_string works on strings, not arrays. Post your code including your problematic query. Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981399 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 Below is the code including the problematic query, I have also provided some comments that might lead to the root of the problem. page2.php <?php require_once("classes/include.all.php");?> <?php //Extract the variable from the url, Here I iterate the arrays to escape them // But as I said the offerings throws a notice post #12 $strName = isset($_REQUEST['frmSearch']['name'])?mysql_real_escape_string($_REQUEST['frmSearch']['name']):''; $strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):''; $strState = isset($_REQUEST['frmSearch']['state'])?mysql_real_escape_string($_REQUEST['frmSearch']['state']):''; $arrFoodTypedata = array(); foreach ($_REQUEST['frmSearch']['food_types'] as $arrFoodTypes) { $arrFoodTypedata[] = mysql_real_escape_string($arrFoodTypes);} $arrOfferingsdata = array(); foreach ($_REQUEST['frmSearch']['offerings'] as $arrOfferings) { $arrOfferingsdata[] = mysql_real_escape_string($arrOfferings);} ?> <?php //Here I had to use two variable which has the same value, the if condition //check wheter if the variable $strZipCode coming from the form in //page1.php is not empty. The else statement makes sure $striZipCodes gets //the value of the appended variable coming from a refresh in page2.php //itself it is the same value as $strZipCode the only thing that $strZipCode is //lost when user paginates through, that's why else REQUEST strZipCode. if (!empty ($strZipCode)){ $strZipCodes = $strZipCode; } else { $strZipCodes = $_REQUEST['strZipCode']; } ?> <?php $setter = true; ?> <div id="container4"> <div class="wrap1"> <?php //Over here is a set of filter to later be use at the query right above the html $boolIncludeZipCodes = false; // Zipcode filter if(!empty($strZipCode)) { $boolIncludeZipCodes = true; $arrSQLFilters[] = sprintf( "r.zip LIKE '%s'" ,"%$strZipCode%" ); } // State filter if(!empty($strState)) { $boolIncludeZipCodes = true; $arrSQLFilters[] = sprintf( "r.state = '%s'" ,$strState ); } // Restaurants name filter if(!empty($strName)) { $arrSQLFilters[] = sprintf( "r.restaurantname LIKE '%s'" ,"%$strName%" ); } // Food types filter if(!empty($arrFoodTypes) && !empty($arrFoodTypes[0])) { $arrSQLFilters[] = sprintf( 'r.restaurants_id IN (SELECT restaurants_id FROM restaurants_restaurant_food_types WHERE restaurants_food_types_id IN (%s) GROUP BY restaurants_id HAVING COUNT(*) = %u)' ,/*mysql_real_escape_string(*/ implode(',',$arrFoodTypes) /*)*/ ,count($arrFoodTypes) ); } // Offerings Filter ie. eat-in, lunch, dinner, etc if(!empty($arrOfferings)) { $arrSQLFilters[] = sprintf( 'r.restaurants_id IN (SELECT restaurants_id FROM restaurants_to_restaurant_offering WHERE restaurants_offerings_id IN (%s) GROUP BY restaurants_id HAVING COUNT(*) = %u)' ,/*mysql_real_escape_string(*/ implode(',',$arrOfferings) /*)*/ ,count($arrOfferings) ); } // get the info from the db, This info coming from the database display in //html, If you see There is a Rating system in <h5> and the code for the //rating system is found insde <h4> which is rating all the string display //inside <h2> <h2 class=\"infohead\">". $arrRestaurant['restaurantname'] . //"</h2>. That indext ['restaurantname'] I believe is an string field which //display the name of the restaurnats, and I think the problem is coming from //there. Some restaurnats has an apostrophe (') in the query string and it //won't INSERT the rating of those string or restaurants names inside the //database. They need to be escaped, I have escaped the string data inside //the Rating class, found at the <h5> tagas Rating::OutputRating. and it is //escaping after echoing the variable inside the Class, which is another file //included in this page2.php but even though it is escaped it won't rated or //INSERT it into the database. It will INSERT or rate all the other string that //won't have an apostrophe (') inside the string. I was wondering if I need //to escape it from the query below instead of the Rating Class? Or what can //be causing it not to INSERT Which is the root problem. The only that php has complain was the a warning. //b>Warning</b>: mysql_real_escape_string() expects parameter 1 to be //string, array given in <b>C:\wamp\www\nyhungry\indexpagination.php</b> //on line <b>12</b><br //line 12 was as //$arrFoodTypes = isset($_REQUEST['frmSearch']//['food_types'])?mysql_real_escape_string($_REQUEST['frmSearch']//['food_types']):array(); // and that was the way it was set up before iterating that array along with //offerings //the rest of the code is as below. $strSQL = sprintf( 'SELECT r.restaurants_id ,r.restaurantname ,r.image ,r.description ,r.address ,r.zip ,r.state FROM restaurants r %s %s %s LIMIT %d, %d' ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':'' ,empty($arrSQLFilters)?'':' WHERE '.implode(' OR ',$arrSQLFilters) ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':'' ,$offset, $rowsperpage ); $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error()); while($arrRow = mysql_fetch_assoc($arrResult)) { $arrRestaurants[] = $arrRow; } $i = 1; foreach($arrRestaurants as $arrRestaurant) { echo "<div class=\"shoeinfo1\"> <img src=\"images/spacer.gif\" alt=\"spacer\" class=\"spacer2\" /> <h2 class=\"infohead\">". $arrRestaurant['restaurantname'] . "</h2> <div class=\"pic\"><img class=\"line\" src= ". $arrRestaurant['image'] ." alt=\"picture\" width=\"100%\" height=\"100%\" /></div> <h5> Rating:</h5><h4>"; $ratingData = Rating::OutputRating ($arrRestaurant['restaurantname']); if (Error::HasErrors()) { echo Error::ShowErrorMessages(); Error::ClearErrors(); } else { echo $ratingData; } echo"</h4> <h3>Description:</h3> <div id=\"description\"><p>".$arrRestaurant['description']." </p></div> <div class=\"suabe2\">Address:<span class=\"suabe\">".$arrRestaurant['address']."</span></div> <div id=\"state\">State:<span class=\"suabe\">". $arrRestaurant['state']. "</span></div> <h6>Zip:<span class=\"suabe\">". $arrRestaurant['zip'] . "</span></h6> <p><a href=\"#\">More</a></p></div> "; $i++; if ($i > 1 && $i % 4 == 0 ) { echo "<div class=\"clearer\"></div>"; } }?> </div> </div> <?php mysql_close($connection); ?> <?php Database::DeInitialize(); ?> <?php include("includes/footer.php"); ?> Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981556 Share on other sites More sharing options...
co.ador Posted December 21, 2009 Author Share Posted December 21, 2009 This is another part where the problem might origin. How can I echo this query ExecuteQuery method? <?php Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating"); Database::FetchResults("InsertRating"); Database::FreeResults("InsertRating"); Database::RemoveSavedResults("InsertRating"); ?> ExecuteQuery method referred in the query above. <?php public static function ExecuteQuery($sql, $name) { if (self::$connection) { if (strlen(trim($name)) != 0) { switch (self::$type) { case "mysql": if (!array_key_exists($name, self::$savedQueries)) { self::$savedQueries[$name] = @mysql_query($sql, self::$connection) or Error::LogError("Query Failed", mysql_error(self::$connection)); } break; case "mysqli": if (!array_key_exists($name, self::$savedQueries)) { self::$savedQueries[$name] = @mysqli_query(self::$connection, $sql) or Error::LogError("Query Failed", mysqli_error(self::$connection)); } break; } return self::$savedQueries[$name]; } else { Error::LogError("Execute Query Name Missing", "The name parameter was empty, please provide a name for the query."); } } return null; } ?> you can see in the link below how the 4th and 6th iteration is being escape but still it won't INSERT iteration where it's query string has an apostrophe in. at the link you will see I have echoed the string to proof it is escaped but still it won't INSERT. http://www.nyhungry.com/indexpagination.php?currentpage=2&strZipCode=10468 Link to comment https://forums.phpfreaks.com/topic/185852-iterating-through-an-array-and-escape-each-value-independently/#findComment-981925 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.