SitePoint Sponsor

User Tag List

Results 1 to 18 of 18
  1. #1
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    iterating through an array and escape each value independently

    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 Code:

    $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 Code:
    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?

  2. #2
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    Bangalore, India
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yo have missed a single quote in this part of the code
    Code:
    foreach($_REQUEST as ['frmSearch]=>'['food_types'])
    
    {$data['frmSearch']=mysql_real_escape_string(['food_types]);}
    Try this (With the missing quote in)
    Code:
    foreach($_REQUEST as ['frmSearch]=>'['food_types'])
    
    {$data['frmSearch']=mysql_real_escape_string(['food_types']);}
    Hope you could identify where the single quote was missed. See if this works
    Thank You
    Known is a Drop, Unknown is an Ocean

  3. #3
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did a print r and the result was.

    Array( [frmSearch] => Array (
    [name] =>
    [zipcode] => 10468
    [state] => NY
    [food_types] => Array
    (
    [0] =>
    )
    [submit] => Submit
    )
    )


    There is an [offerings] index as well which should be inside the print_r display above. The following warning below might give an idea why the index [offerings] is not displaying


    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
    Does any body knows if those notice and warning might be preventing the offerings index to display at the print_r above?

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    Bangalore, India
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But did the quote solve the problem at first step ? Was the correction correct ?
    Thank You
    Known is a Drop, Unknown is an Ocean

  5. #5
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the set up of the script was wrong it supposed to be like

    PHP Code:
    foreach ($_REQUEST['frmSearch']['food_types'] as $arrFoodTypes) {  $data[] = mysql_real_escape_string($arrFoodTypes);} 

  6. #6
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    Bangalore, India
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by co.ador View Post
    the set up of the script was wrong it supposed to be like

    PHP Code:
    foreach ($_REQUEST['frmSearch']['food_types'] as $arrFoodTypes) {  $data[] = mysql_real_escape_string($arrFoodTypes);} 
    Thanks
    Thank You
    Known is a Drop, Unknown is an Ocean

  7. #7
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually not single quote missed but whole syntax is spoiled. As usual

    co.ador
    some hints for your own work
    - you have to iterate $_REQUEST['frmSearch'] variable. Not $_REQUEST.
    - read manual entry for http://php.net/foreach , try to execute and understand examples
    - you need extended foreach syntax

  8. #8
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    oh no.
    there is a nested array

  9. #9
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    and you as usual with your quick remarks, if you see on post 4 I have inserted the correct version of iteraring.

  10. #10
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yes, for the food_types it is correct

  11. #11
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    Bangalore, India
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But did the quote solve the problem at first step ? Was the correction correct ?
    Thank You
    Known is a Drop, Unknown is an Ocean

  12. #12
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wander why a similar iteration structure for offerings would throw the following notice and warning, when in the form name property is equal to offerings.

    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
    i guess is becuase I have used the variable $data for both iterations?

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by co.ador View Post
    I wander why a similar iteration structure for offerings would throw the following notice and warning, when in the form name property is equal to offerings.
    Would you care to update us as to the code you're currently using?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    nothing bad with $data.
    but to answer your question line 16 of indexpagination.php script must be shown here

  15. #15
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Below is the page2.php and I have provided some comment that might lead to the root of the problem.

    page2.php
    PHP Code:
    <?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 && $i == 
    {
      echo 
    "<div class=\"clearer\"></div>";

    }
    }
    ?>

    </div>
    </div>
    <?php 
    mysql_close
    ($connection);
    ?>
    <?php
      Database
    ::DeInitialize();
    ?>


    <?php include("includes/footer.php"); 
    ?>

  16. #16
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One 16th line. Not whole lot.
    Notice: Undefined index: offerings in C:\wamp\www\nyhungry\indexpagination.php on line 16
    there are no field 'offerings' in the $_REQUEST['frmSearch'] array

  17. #17
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First of all i would recommend to use particular global array (GET or POST) for your purpose instead of REQUEST. Secondly if you are supposing just to use that mysql_real_escape_string to each of the values of an array then why not go for array_map():
    PHP Code:
    $data $_POST['frmSearch']['food_types']; // $_POST['frmSearch']['food_types'] supposed to be an array
    $data array_map('mysql_real_escape_string'$data); 
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  18. #18
    SitePoint Wizard co.ador's Avatar
    Join Date
    Apr 2009
    Posts
    1,054
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried the map array and it works ok, just as the extracting code on top of the script at the former post, array map will only accept arrays as it supposed to. but still the original problem persists it Won't it INSERT a given string with an apostrophe, still looking for the spot causing the issue.

    I have tried to echo the query in the ExecuteQuery method to see if it's possible to see if there is something wrong the query.?

    PHP Code:
     
        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 Code:
    <?php
     
    public static function ExecuteQuery($sql$name)
         
          {
            if (
    self::$connection)
            {
              if (
    strlen(trim($name)) != 0)
              {
                switch (
    self::$type)
                {
                  case 
    "mysql":
                    if (!
    array_key_exists($nameself::$savedQueries))
                    {
                      
    self::$savedQueries[$name] = @mysql_query($sqlself::$connection) or Error::LogError("Query Failed"mysql_error(self::$connection));
                    }
                    break;
                  case 
    "mysqli":
                    if (!
    array_key_exists($nameself::$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/indexpaginat...rZipCode=10468


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •