Page 1 of 1

convert URL string to array

Posted: Sat Jun 16, 2007 1:29 am
by psm9640
Before I spend a lot of time on this I want to get some input on possible ways to handle this...

I have a client who is using a third part shopping cart on their site. At the end of every transaction, there is a silent post back to the server where the site is hosted that allows me to capture the order #, address info, etc. Everything is clearly separated with an ampersand, BUT for each item someone has purchased, rather than giving you an array (...item[]=gold%20watch&item[]=belt&20buckle...) they have already assigned variables of item1=, item2=, etc.

So my question is, rather than having a bunch of $_POST variables predefined, is there a way to break these out into an array so I can run a loop so that no matter how many items someone buys, I don't have to create a huge number of table fields in the database to accomodate this?

-PM

Posted: Sat Jun 16, 2007 1:54 am
by Gente
Try this example from PHP Manual

Code: Select all

<?php
$a = explode('&', $_SERVER['QUERY_STRING']);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'Value for parameter ', htmlspecialchars(urldecode($b[0])),
         ' is ', htmlspecialchars(urldecode($b[1])), "<br />\n";
    $i++;
}
?>

Posted: Sat Jun 16, 2007 8:04 am
by feyd
split() is a no, no. explode() or preg_split().

Well.. you can foreach() $_POST, or use parse_str(), or get creative with preg_replace() and parse_str().

Posted: Sat Jun 16, 2007 10:25 am
by psm9640
Thanks guys -- I thought regular expressions might be the way to go. I will give it a whirl but if anything comes to mind that you think would aid this by all means, please enlighten me.

-PM

Posted: Sat Jun 16, 2007 3:19 pm
by psm9640
Well, all I had to do was perform a str_replace on the $key variable generated by the while loop, and then determine if it's an item via if/else statement. If it is an item, it will insert the items into a separate table and if not, I'll put it in a larger query further down in the script (haven't written that yet):

Code: Select all

$ar=$_GET;
while (list($key,$val) = each($ar))
{
$newKey = substr_replace($key, '', 4);
if($newKey=="item") { $key = "item"; 

//if this is an item I'm going to write it to a separate table anyway so do the query...
mysql_select_db($mysql);
$item_query = "INSERT INTO order_items ('','$_GET[order_num]','$val')";
mysql_query($item_query) or die('Error, insert query failed');
echo '<p>',$item_query;

}
else { echo "$key=$val<br>"; }
}