okay, so i have a search form that has some optional fields, so when the form is submitted using the GET method to its processing php page, the resulting URL may have blank values in it, and it gets quite long.

What id like to know is is there a way to either get the form to ignore the blank form fields when you submit the form, or to have the form processing page rewrite the URL to remove the blank key/value pairs?

I would use POST except that i need to paginate the results, and using POST makes this impossible AFAIK (as the minute you go to say page 2 the POST variables are lost) without using SESSION variables or a cookie...not great either when users may want to bookmark the results pages

Any help would be greatly appreciated

The $_GET will always post the blank values so your bet bet would be to remove the empty parameter values in the processing page after you have declared them in trimmed variables, simply call the empty function. As far as removing an empty parameter value from the $_GET.

You could remove the empty variables, recreate the string and redirect to another processing page.

Regards

A.Romano

Hey.

You could use Javascript to process the the form for you.
Something like this should do it:

function SubmitForm(pForm) {
    var getString = "";

    var elems = pForm.getElementsByTagName('input');
    for(var i = 0; i < elems.length; i++) {
        if(elems[i].value != "") {
            getString += encodeURIComponent(elems[i].name) + "=" + encodeURIComponent(elems[i].value) + "&";
        }
    }

    window.location = pForm.action + getString;
    return false;
}

Then you would just add this to the onsubmit event for the form.

<form action="?" method="get" onsubmit="SubmitForm(this);">

Ohh, forgot the submit button.

If you don't want the button submitted as well, add this to the for loop:

if(elems[i].type == "submit") {
    continue;
}

thanks for the quick replies people

ill look into your suggestions after a bit of a snooze, i just wanted to say a quick thanks for the very quick suggestions

Hey.

You could use Javascript to process the the form for you.
Something like this should do it:

function SubmitForm(pForm) {
    var getString = "";

    var elems = pForm.getElementsByTagName('input');
    for(var i = 0; i < elems.length; i++) {
        if(elems[i].value != "") {
            getString += encodeURIComponent(elems[i].name) + "=" + encodeURIComponent(elems[i].value) + "&";
        }
    }

    window.location = pForm.action + getString;
    return false;
}

Then you would just add this to the onsubmit event for the form.

<form action="?" method="get" onsubmit="SubmitForm(this);">

I hate to say that it doesnt work, nothing gets removed :(

I hate to say that it doesnt work, nothing gets removed :(

Ahh ok. It seems you have to have the onclick even actually return false , or the form will be submitted regardless of the window.location inside the function. I though having the function return false would be enough to prevent the form itself from being submitted, but no.

Anyhow, this works for me.

<!DOCTYPE html>
<html>
    <head>
        <title>JS test</title>
        <meta http-equiv="content-type" content="text/html; charset=utf8">
        <script type="text/javascript">
function SubmitForm(pForm) {
    var getString = "";
    var elems = pForm.getElementsByTagName('input');
    for(var i = 0; i < elems.length; i++) {
        if(elems[i].type == "submit") {
            continue;
        }
        if(elems[i].value != "") {
            getString += encodeURIComponent(elems[i].name) + "=" + encodeURIComponent(elems[i].value) + "&";
        }
    }
    window.location = pForm.action + getString;
    return false;
}
        </script>
    </head>
    <body>
        <form action="?" method="get" onsubmit="return SubmitForm(this);">
            <input type="text" name="first"><br />
            <input type="text" name="second"><br />
            <input type="text" name="third"><br />
            <input type="submit">
        </form>
    </body>
</html>
Member Avatar for diafol

Why don't you set empty values to null?

e.g.

if((isset($_POST['whatever']) && $_POST['whatever'] == '') || !isset($_POST['whatever'])){
   $whatever = "&whatever=null";
}else{
  $value = $_POST['whatever'];
  $whatever = "&whatever=$value";
}

then just build the querystring from all the individual key-value pairs.

Why don't you set empty values to null?

How is the processing page supposed to know if the value of the field is supposed to be NULL (absence of data) or if it is actually supposed to be the string "null"?
Makes much more sense to just leave the field out altogether.

In any case, this is purely a cosmetic thing (I presume), so setting it to null is not really an improvement over leaving it empty.

But you could of course use PHP code, similar to your example, to do server-side what my Javascript example is meant to do client-side. It could at least serve as a fallback for browsers that don't execute Javascript code.

Member Avatar for diafol

How is the processing page supposed to know if the value of the field is supposed to be NULL (absence of data) or if it is actually supposed to be the string "null"?
Makes much more sense to just leave the field out altogether.

Fair enough, leaving it out altogether is another (possibly better) option. Like you said the use of 'null' is purely cosmetic. Thinking about it, since the querystring could be changed manually anyway, it wouldn't really save on $_GET processing.

thanks for the suggestions

in the end i decided to go the rewrite header path, as it was easier and didnt involve client side processing, and this sort of stuff probably isnt best handled by end users :P

i had posted the same query here on another board (phpfreaks) and before i could craft my own rewrite header routine, a very nice member there (GarethP) posted one that worked a treat and importantly worked on a GET URL with array elements in it!

Saved me a bit of time. I then had to create a routine to process the GET URL into a WHERE clause for use in a MySQL query and dealt with the array issue.

The rewrite header code follows, and in the interest of sharing and by way of thanks for your help, ive included the GET to WHERE function i wrote. Ive commented it fully as i wrote it, so should be easy to understand. Probably a few ways to do the same thing, probably even in fewer lines, but im relatively new to php, so ifigure its not the worst bit of code about.

rewrite header (rewrite GET string) function:

function Check($Input)
   {
   foreach($Input as $k=>$v)
      {
      if(is_array($v))
         {
         $Input[$k] = Check($v);
         }
      else
         {
         if(!preg_match("~\S~", $v))
            {
            unset($Input[$k]);
            }
         }
      }
   return $Input;
   }

function Make2($Input, $Start)
   {
   $Output = "";
   foreach($Input as $k=>$v)
      {
      if(is_array($v))
         {
         $S = $Start . "[" . $k . "]";
         $Output .= Make2($v, $S);
         }
      else
         {
         $Output .= $Start . "[" . $k . "]=" . $v . "&";
         }
      }
   return $Output;
   }

function Make($Input)
   {
   $Output = "";
   foreach($Input as $k=>$v)
      {
      if(is_array($v))
         {
         $Output .= Make2($v, $k);
         }
      else
         {
         $Output .= $k . "=" . $v . "&";
         }
      }
   $Output = substr_replace($Output,"",-1);
   return $Output;
   }

$GET2 = Check($_GET);

if($GET2 != $_GET)
   {
   $URL = $_SERVER["SCRIPT_NAME"];
   $URL .= "?";
   $GET2 = Make($GET2);
   $URL .= $GET2;
   header("Location: " . $URL);
   }
?>

GET to WHERE clause function:

function createwhereclause( $array ) { 
//split the array into key=>value pairs
foreach( $array as $key => $value ) { 
//if there is a get key, and its not empty or NULL, then process it
//although the above rewrite code eliminates blank entries, i like  //to be comprehensive. but for people not using the rewrite code //above its valid.
If (isset($_GET[$key]) && !empty($value) || ($value==!NULL)){
//check is the value of the current key is an array, if so process it
//ARRAY SECTION
if ( is_array($value) ) { 
//iterate through the key=>value pairs of the array
foreach ($value as $key2 => $newvalue){
//for the first element of the array, we need the operator to be and //AND, in case this 
//array key=>value pair is appended to an exisiting WHERE clause //generated by an non array key=>value pair
if ($key2==0){
$operator =" AND "; 
}else{
//for all key=>value pairs in the array, we need the operator to be //OR
$operator =" OR "; 				
}
//create the WHERE clause, its cumulative, if no WHERE clause //exists, we start one
//the first line opens the WHERE clause
//the second line inserts the first key=>value pair
//the last line appends any remaining key=>value pairs, seperated //by the OR operator
$where .= ($where == "") ? "where
".$key ."='".addslashes($newvalue)."'" :
$operator.$key ."='".addslashes($newvalue)."'";  		    
}
} else{
//NON-ARRAY SECTION
//not a lot of processing to do here
//set the operator to AND
$operator =" AND "; 
//create the WHERE clause, its cumulative, if no WHERE clause //exists, we start one
//the first line opens the WHERE clause
//the second line inserts the first key=>value pair
//the last line appends any remaining key=>value pairs, seperated //by the AND operator
$where .= ($where == "") ? "where
".$key ."='".addslashes($value)."'" :
$operator.$key ."='".addslashes($value)."'";  	
}
}else{
}
}
//return the WHERE clause for inclusion into a mysql SELECT query
return $where;
}

Its used on the site im building to list real estate properties, so it searches on columns iin the database as opposed to a keyword search. And as such ive created a form with the suburbs dynamically read form the db and presented as checkboxes for multiple selections, hence the array stuff mentioned earlier.

so i use the search form, which submits to the searchresults.php page which houses the following code.

i use the rewrite header code at the top of the searchresults.php file, then the GET to WHERE function appears.

Then i call the Get to WHERE function like this: $where = createwhereclause($_GET); The use the $where variable in the mysql query like this: $query1 = mysql_query("SELECT * FROM houses ". $where); and then onto the display code

Hope this isnt boring and is somehow useful to others in future.

p.s. Sorry for the formatting, it was well laid out but as usual i had to rejig it as long lines get mangled in forum posts :)

I have the same issue, either POST or GET, when running the codes in localhost, they give me empty values but everything works fine when running them to my hosting..weird.. I'm now doing some back ups, will reinstall my localhost server.. any help please.. thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.