How to pass PHP array via POST

By: Kevin | May 5, 2014

I was working on a site which had two databases and different domain names. My problem was I needed to pass information from one database (domain) to another. I wasn’t sure the best way to approach this but finally came to this conclusion. So here it is.

//Select your data from the source
$sql = "Select * from orders where Id='$orderid'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);//$row is an array

So now we have our data in $row.

Next we will use the PHP function serialize. This function takes our array and turns it into a string representation of the data, or a bit stream. More on the serialize function here.

This doesn’t quit get us there. By using the serialize function we caused another problem. Our array is now a string with a lot of quotes (“) in it. The quotes don’t mesh well within a form and prevent a large amount from being passed to the other page.

To remove the quotes I use another php function called urlencode. urlencode is a straight forward function, it takes a string and replaces the quotes with html safe characters. More on urlencode here.

<form action="somepage.php" method="post">
//I have nested my calls to urlencode and serialize
//in the value below
<input name="row" value="<?=urlencode(serialize($row))?>" />
<input type="submit" value="Save">
</form>

After this form is submitted, we do the opposite to get our original array back. Be sure to do this in reverse order.

//unserialsize data coming from previous page
$row = unserialize(urldecode($_POST['row']));

Ta-Da! Now you have the original array and the data from the previous database.