PHP Tip of the Day - Query Builder

Status
Not open for further replies.

smaxor

New member
Oct 17, 2006
2,514
87
0
San Diego
Don't know how many of you know about this function but it's beautiful.

http_build_query();

Basically you pass it a hash of field=>value and it does the urlencoding and generatres a nice post string. For example:

<?
$myarray = array('field1'=>'value1','field2'=>'value2');
$poststring = http_build_query($myarray);
echo $poststring;
?>

and you'll get the output:

field1=value1&field2=value2

That's a very simple one but I coded for a few years before I found this function. Works great and is a internal PHP fuction so you know it's fast and doesn't have bugs.

enjoy!
 
  • Like
Reactions: nickycakes


You can manage the internal hash programmatically and just turn it into a string whenever you want without doing string manipulation... That's awesome!
 
Just be sure to always put your parameters in order the same way every time. You may think that with querystring, you can stick them in any order, since you probably access them with the key name, but if you are putting URLs out that could be spidered, you could end up with 'duplicate content' by reversing one or more of the key positions...

http://.../?a=1&b=2
http://.../?b=2&a=1

two different URLs...

Also, unless you are using numeric index arrays, PHP does not always return keyword arrays in the exact same order... Or I should say it is advised not to assume the order returned. Believe I read it in the manual at some point.
 
For those of you with PHP4...here's a copy of the function

Code:
function  http_build_query($aArgs)
{
$sRequestPairs = "?";
foreach ($aArgs as $sLabel => $sValue)
{
$sRequestPairs .= urlencode($sLabel).'='.urlencode($sValue).'&';
}
$sRequestPairs = substr($sRequestPairs,0,strlen($sRequestPairs)-2);
return $sRequestPairs;
}

Untested.

Jason
 
Status
Not open for further replies.