www.webdeveloper.com
Results 1 to 15 of 15

Thread: foreach loop in query based on form selection

  1. #1
    Join Date
    Mar 2007
    Posts
    44

    foreach loop in query based on form selection

    I have search form with a filter function, the search form has the following fields (name of the fields):

    upme_search[zip_code] -> Zipcode field

    upme_search[sport_distance] -> range of kilometers to search from entered zipcode

    upme_search[account_type][] -> 2 checkboxes with values: Trainer and Sportvereniging

    upme_search[user_sports][] -> List of sports to chose from

    upme_search[user_city] -> City to enter


    Now when I enter my zipcode and select distance, I get the profiles that are within the range selected.

    But when I check beside the entered zipcode and selected distance, a checkbox, the checkbox is not included in the search query.

    Here is part of the code I use for the query:

    PHP Code:
    if (is_in_post('upme_search')) {  
                      
                    foreach (
    $_POST['upme_search'] as $key => $value) {  
                        if(
    $_POST['upme_search']['zip_code'] != '' && $_POST['upme_search']['sport_distance'] != '' ){ 
                            continue;  
                        }  

                        
    $process false;  

                        if (
    is_array($value) && count($value) > 0)  
                            
    $process true;  
                        else if (
    $value != '' && $value != '0')  
                            
    $process true;  
                        else  
                            
    $process false;  

                        if (
    $process === true) {  
                            if (
    is_array($value)) {  

                                foreach (
    $value as $k => $v) {  
                                  
                                    
    $this->search_query_search_param[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql(trim($v)) . "%')";  
                                }  
                            } else {  
                                  
                                
    $this->search_query_search_param[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql($value) . "%')";  
                            }  
                        }  
                    }  


                    if(
    $_POST['upme_search']['zip_code'] != '' && $_POST['upme_search']['sport_distance'] != '' ){  
             
                        
    $value1 $_POST['upme_search']['zip_code'];  
                        
    $distance $_POST['upme_search']['sport_distance'];  
                        
    $auth_key "unique ID";  
                        
    $nl_fourpp $value1;  

                        
    // Optionally, set a timeout (in ms)  
                        
    $timeout 150000;  

                        
    $url "http://api.pro6pp.nl/v1/range?auth_key=" $auth_key .  
                               
    "&nl_fourpp=" urlencode($nl_fourpp) .   
                               
    "&range=" $distance "&per_page=1000";  

                        
    $ch curl_init();  
                        
    curl_setopt($chCURLOPT_RETURNTRANSFER1);   
                        
    curl_setopt($chCURLOPT_URL$url);  
                        
    curl_setopt($chCURLOPT_TIMEOUT_MS$timeout);  

                        
    $result curl_exec($ch);  
                        
    curl_close($ch);  

                        if (
    $result)  
                        {  
                          
    // Show raw output  
                          //echo "Output: " . $result . "<br/>";  

                          
    $output json_decode($result);  
                          
    $status $output->{"status"};  

                          if (
    $status === "ok")  
                          {  
                            
    //print("Found results:<br/><br/>");  
                            
    foreach ($output->{"results"} as $value)  
                            {  

                                
    $this->search_query_search_param2[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%zip_code::" $value->{"nl_fourpp"} . "%' AND mt.meta_key = '_upme_search_cache' AND mt.meta_value <> "$value->{"distance"} . " AND mt.meta_key = '_upme_search_cache' AND mt.meta_value <= "$distance ")";  

                            }  
                          }  
                          else  
                          {  
                            
    // Error.  
                            
    $message $output->{"error"}->{"message"};  
                            echo 
    "Error message: " $message;  
                          }  
                        } else {  
                          
    // Timeout occured. Either the service is down or you should  
                          // increase the timeout to at least 150000ms.  
                          
    echo "Pro6PP is unavailable at this time";  
                        }  


                    }  

                } 
    So what this does or should do is, when the zipcode and distance are not empty the foreach loop (regular loop for the search form) should skip the zipcode and distance field and procede (if needed) with any other fields entered or selected.

    If the zipcode and distance are not empty the second part is where the zipcodes within the distance of the selected value is being calculated (using the pro6pp code), this works fine, but if I entered or selected any other field beside the zipcode and distance fields, those fields are not included in the query.

    There seems to be something wrong with the code or the way it is build.

    Please help.

  2. #2
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    Why the convoluted names for your form elements? Arrays are useful with checkboxes or multiple fields collecting similar data items, but not the way your are using them. Plus - you begin a loop trying to examine each of these fields but immediately single out two specific fields on EACH pass thru the loop. Why?

    Drop the array and simply examine your input fields by their names. Simplify!
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  3. #3
    Join Date
    Mar 2007
    Posts
    44
    Thanks for the reply.

    So what you're saying is going from a dynamic array (using the foreach), to a static one, checking each field seperate and adding them to the query if there are set.

  4. #4
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    All I'm saying is simplify your code by using unique names instead of creating a worthless array of names stored in the POST array. You save nothing in this case by using an array since each of the items is distinct and most likely requires different validations.

    I see your account_type and sports are indeed multiple inputs of the same type of data and can benefit (and most likely require) from array names, so leave those two alone. But simplify still - try using name='account_type[]' and 'user_sports[]' in your html.
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  5. #5
    Join Date
    Mar 2007
    Posts
    44
    I have made some changes to the code, but they are not added to the query, do I miss anything?

    PHP Code:
    $query_search '';

                if(
    $_POST['zip_code'] != '' && $_POST['sport_distance'] != '' ){

                    
    $value1 $_POST['zip_code'];
                    
    $distance $_POST['sport_distance'];
                    
    $auth_key "iRqzCDp5bOiIOCsU";
                    
    $nl_fourpp $value1;

                    
    // Optionally, set a timeout (in ms)
                    
    $timeout 150000;

                    
    $url "http://api.pro6pp.nl/v1/range?auth_key=" $auth_key .
                           
    "&nl_fourpp=" urlencode($nl_fourpp) . 
                           
    "&range=" $distance "&per_page=1000";

                    
    $ch curl_init();
                    
    curl_setopt($chCURLOPT_RETURNTRANSFER1); 
                    
    curl_setopt($chCURLOPT_URL$url);
                    
    curl_setopt($chCURLOPT_TIMEOUT_MS$timeout);

                    
    $result curl_exec($ch);
                    
    curl_close($ch);

                    if (
    $result)
                    {
                      
    // Show raw output
                      //echo "Output: " . $result . "<br/>";

                      
    $output json_decode($result);
                      
    $status $output->{"status"};

                      if (
    $status === "ok")
                      {
                        
    //print("Found results:<br/><br/>");
                        
    foreach ($output->{"results"} as $value)
                        {

                            
    $this->search_query_search3[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%zip_code::" $value->{"nl_fourpp"} . "%' AND mt.meta_key = '_upme_search_cache' AND mt.meta_value <> "$value->{"distance"} . " AND mt.meta_key = '_upme_search_cache' AND mt.meta_value <= "$distance ")";

                        }

                        
    $query_search .= ' AND '$orderby_meta_where implode(' OR '$this->search_query_search3);

                      }
                      else
                      {
                        
    // Error.
                        
    $message $output->{"error"}->{"message"};
                        echo 
    "Error message: " $message;
                      }
                    } else {
                      
    // Timeout occured. Either the service is down or you should
                      // increase the timeout to at least 150000ms.
                      
    echo "Pro6PP is unavailable at this time";
                    }

                }

                
    // Build the zipcode query based on zipcode field entry
                
    if($_POST['zip_code'] != '' && !$_POST['sport_distance']){

                    
    $query_search .= " AND mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%zip_code::" esc_sql($_POST['zip_code']) . "%'";

                }

                if(
    $_POST['account_type']) {

                    foreach (
    $_POST['account_type'] as $key => $value) {
                        
    $process false;

                        if (
    is_array($value) && count($value) > 0)
                            
    $process true;
                        else if (
    $value != '' && $value != '0')
                            
    $process true;
                        else
                            
    $process false;

                        if (
    $process === true) {
                            if (
    is_array($value)) {

                                foreach (
    $value as $k => $v) {
                                
                                    
    $this->search_query_search2[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql(trim($v)) . "%')";
                                }
                            } else {
                                
                                
    $this->search_query_search2[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql($value) . "%')";
                            }
                        }
                    }

                    
    $query_search .= ' AND '$orderby_meta_where implode(' ' $this->search_args['operator'] . ' '$this->search_query_search2);
                }

                if(
    $_POST['upme_search']['user_sports']){

                    foreach (
    $_POST['upme_search']['user_sports'] as $key => $value) {
                        
                        
    $process false;

                        if (
    is_array($value) && count($value) > 0)
                            
    $process true;
                        else if (
    $value != '' && $value != '0')
                            
    $process true;
                        else
                            
    $process false;

                        if (
    $process === true) {
                            if (
    is_array($value)) {

                                foreach (
    $value as $k => $v) {
                                
                                    
    $this->search_query_search[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql(trim($v)) . "%')";
                                }
                            } else {
                                
                                
    $this->search_query_search[] = "(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%" $key '::' esc_sql($value) . "%')";
                            }
                        }
                    }
                    
    $query_search .= ' AND '$orderby_meta_where implode(' ' $this->search_args['operator'] . ' '$this->search_query_search);
                }

                if(
    $_POST['user_city'] != ''){

                    
    $query_search .= " AND mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%user_city::" esc_sql($_POST['user_city']) . "%'";

                }

                
    $this->search_query_search_param2 $query_search
    The search_query_search_param2 is added to the final query as followed:

    PHP Code:
    if ($this->search_query_search_param2) {

            
    $this->search_query_string.= $search_query_search_param2;

            
    $this->count_search_query_string.= $search_query_search_param2;

    search_query_string is a query where are the 'extra' filters are put together.
    Last edited by UD2006; 07-26-2014 at 07:55 AM.

  6. #6
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    How about showing us the whole thing - or at least the form that you are processing in the php above? I'm not going to try and analyze something that I don't know all the details about.
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  7. #7
    Join Date
    Mar 2007
    Posts
    44
    Hi,

    Your right, the following is code of a function, the file would be too large to show, hope this gives more insight on how it works:

    I have attached the file where the function is in (it was too long to post).

    temp3.php.zip

    Thanks for any help.

  8. #8
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    No. I don't want to see anything too long, but on the other hand your form itself cannot be too long to post here.
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  9. #9
    Join Date
    Mar 2007
    Posts
    44
    What do you need exactly, the html of the form or the php generated version?

  10. #10
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    I want to see the html form code. What are you talking about? Your php shouldn't need to be involved in outputting your html - afterall it's just a form.
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  11. #11
    Join Date
    Mar 2007
    Posts
    44
    Why I asked it because the whole code is part of a wordpress plugin and the form has been generated through php.

    So here is the form itself:

    Code:
    <form action="" method="post" class="pro6pp_range"><h3>FILTER</h3><input type="text" class="postcode zip" value="1951" name="zip_code" placeholder="VUL HIER UW POSTCODE IN"><p>IN EEN STRAAL VAN (KM)</p><select name="sport_distance" class="range upme-search-meta-sport_distance">
                            <option value="" selected="selected">Selecteer afstand</option>
                            <option value="5000">5 km</option>
                            <option value="10000">10 km</option>
                            <option value="15000">15 km</option>
                            <option value="25000">25 km</option>
                            <option value="50000">50 km</option>
                            </select><div class="checkbox"><label><input type="checkbox" name="account_type[]" class="upme-search-meta-account_type" value="Trainer"> Trainer</label></div><div class="checkbox"><label><input type="checkbox" name="account_type[]" class="upme-search-meta-account_type" value="Sportvereniging"> Sportvereniging</label></div><p>SPORT(EN) WAAR U NAAR ZOEKT</p><select class="upme-search-input upme-search-multiselect upme-search-meta-user_sports" name="upme_search[user_sports][]" multiple="multiple"><option value="">SPORTEN</option><option value="Acrobatiek">Acrobatiek</option><option value="Aerobics">Aerobics</option><option value="Aikido">Aikido</option><option value="Atletiek">Atletiek</option><option value="Badminton">Badminton</option><option value="Ballet">Ballet</option><option value="Basketbal">Basketbal</option><option value="Beachvolleybal">Beachvolleybal</option><option value="Bewegen voor ouderen">Bewegen voor ouderen</option><option value="Bobsleeen">Bobsleeen</option><option value="Body attack (groepsfitness)">Body attack (groepsfitness)</option><option value="Body balance (groepsfitness)">Body balance (groepsfitness)</option><option value="Body combat (groepsfitness)">Body combat (groepsfitness)</option><option value="Body jam (groepsfitness)">Body jam (groepsfitness)</option><option value="Body pump (groepsfitness)">Body pump (groepsfitness)</option><option value="Body shape (groepsfitness)">Body shape (groepsfitness)</option><option value="Boksen">Boksen</option><option value="Boogschieten">Boogschieten</option><option value="Bootcamp">Bootcamp</option><option value="Bowlen">Bowlen</option><option value="Breakdance">Breakdance</option><option value="Bridge">Bridge</option><option value="Cricket">Cricket</option><option value="CrossFit">CrossFit</option><option value="Curling">Curling</option><option value="Dansen">Dansen</option><option value="Darten">Darten</option><option value="Discuswerpen">Discuswerpen</option><option value="Duiken">Duiken</option><option value="Fight Yoga">Fight Yoga</option><option value="Fitness">Fitness</option><option value="Footgolf">Footgolf</option><option value="Gewichtheffen">Gewichtheffen</option><option value="Golf">Golf</option><option value="Golfsurfen">Golfsurfen</option><option value="Grit (groepsfitness)">Grit (groepsfitness)</option><option value="Handbal">Handbal</option><option value="Hardlopen">Hardlopen</option><option value="Hockey">Hockey</option><option value="Honkbal">Honkbal</option><option value="Hoogspringen">Hoogspringen</option><option value="Hordelopen">Hordelopen</option><option value="IJshockey">IJshockey</option><option value="Jazzdance">Jazzdance</option><option value="Jiu Jitsu">Jiu Jitsu</option><option value="Judo">Judo</option><option value="Kanovaren">Kanovaren</option><option value="Karate">Karate</option><option value="Kickboksen">Kickboksen</option><option value="Kitesurfen">Kitesurfen</option><option value="Korfbal">Korfbal</option><option value="Krav Maga (zelfverdediging)">Krav Maga (zelfverdediging)</option><option value="Kunstschaatsen">Kunstschaatsen</option><option value="Les mills (groepsfitness)">Les mills (groepsfitness)</option><option value="Motorsport">Motorsport</option><option value="Mountainbiken">Mountainbiken</option><option value="Naschoolse opvang activiteiten">Naschoolse opvang activiteiten</option><option value="Nordic walking">Nordic walking</option><option value="Paardenrijden">Paardenrijden</option><option value="Pencak cilat">Pencak cilat</option><option value="Personal training">Personal training</option><option value="Pilates (groepsfitness)">Pilates (groepsfitness)</option><option value="Polo">Polo</option><option value="Roeien">Roeien</option><option value="Rugby">Rugby</option><option value="Schaatsen">Schaatsen</option><option value="Schaken">Schaken</option><option value="Schermen">Schermen</option><option value="Schoonspringen">Schoonspringen</option><option value="Shíbam (groepsfitness)">Shíbam (groepsfitness)</option><option value="Skeeleren">Skeeleren</option><option value="SkiŽn">SkiŽn</option><option value="Snowboarden">Snowboarden</option><option value="Softbal">Softbal</option><option value="Spinning (groepsfitness)">Spinning (groepsfitness)</option><option value="Sport en spel voor kinderen">Sport en spel voor kinderen</option><option value="Sportmassage">Sportmassage</option><option value="Speerwerpen">Speerwerpen</option><option value="Squash">Squash</option><option value="Stand up paddling">Stand up paddling</option><option value="Stepdance">Stepdance</option><option value="Stijldance">Stijldance</option><option value="Streetdance">Streetdance</option><option value="Sumoworstelen">Sumoworstelen</option><option value="Surfen">Surfen</option><option value="Tae bo">Tae bo</option><option value="Taekwando">Taekwando</option><option value="Tafeltennis">Tafeltennis</option><option value="Tai Chi">Tai Chi</option><option value="Tennis">Tennis</option><option value="Thaiboksen">Thaiboksen</option><option value="Turnen">Turnen</option><option value="Verspringen">Verspringen</option><option value="Voedingscoach">Voedingscoach</option><option value="Voetbal">Voetbal</option><option value="Volleybal">Volleybal</option><option value="Wakeboarden">Wakeboarden</option><option value="Wandelen">Wandelen</option><option value="Waterpolo">Waterpolo</option><option value="Waterskien">Waterskien</option><option value="Waveboarden">Waveboarden</option><option value="Wielrennen">Wielrennen</option><option value="Windsurfen">Windsurfen</option><option value="Worstelen">Worstelen</option><option value="Xco (groepsfitness)">Xco (groepsfitness)</option><option value="Yoga">Yoga</option><option value="Zeilen">Zeilen</option><option value="Zumba">Zumba</option><option value="Zwemmen">Zwemmen</option></select><span class="small-info">Selecteer meerdere sporten door de CTRL toets ingedrukt te houden.</span><p>PLAATS</p><input type="text" class="upme-search-meta-user_city" value="" name="user_city" placeholder="WOONPLAATS"><input type="hidden" name="userspage" id="userspage" value=""><input type="hidden" name="submit-search-area" id="submit-search-area" value="1"><input type="submit" class="btn header-btn button" name="upme-search" value="ZOEK"></form>
    There is alot of dutch text in it, so if you need any explanation, I am happy to do that.

  12. #12
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    You still have a problem with the name of upme_search. You have an array and a single element with that name. That's a problem.

    I don't really understand your code, but here's what I see that could be improved.

    account_type and upme_search are arrays. Period. So all you need to do to handle them is

    PHP Code:
    foreach ($_POST['account_type'] as $value)
    {
    (
    build your search string for your query)
    }
    foreach (
    $_POST['upme_search'] as $value)
    {
    (
    build your search string for your query)

    Also - you are using a multi-dimensional array still. No need to do that.Your html should be simply

    name='upme_search[]'
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  13. #13
    Join Date
    Mar 2007
    Posts
    44
    Thanks, yeah I noticed those mistakes, but I also excluded 2 roles from the query so they should not end up in the profiles, but they still do. The roles are "administrator" and "sportentrainer".

    In the code those lines look like:

    PHP Code:
    array_push($search_user_status_filters"(mt.meta_key = '_upme_search_cache' AND mt.meta_value NOT LIKE '%role::administrator%')");
                
    array_push($search_user_status_filters"(mt.meta_key = '_upme_search_cache' AND mt.meta_value NOT LIKE '%role::sportentrainer%')"); 
    role::administrator and role::sportentrainer are this way because they are saved that way in the database by the wordpress plugin.

  14. #14
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    731
    I have no idea what your last post was about.

    I'm losing interest. Good bye
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL | E_NOTICE);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  15. #15
    Join Date
    Mar 2012
    Posts
    1,520
    If you have got a problem with WordPress (or a WP plugin) Please say so in the OP, and post in the CMS forum. Thread moved.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles