Array Serialization and Unserialization in PHP and MySQL
Posted: Thu May 28, 2009 5:18 pm
I have some data which is in an array to be serialized going into a database and then I want to retrieve the information and display it. I am working an example found on this site.
You are given a set of four checkboxes which you click and press submit. The information is supposed to be written to the database (which it does) and then retrieved and printed to the screen. The problem I appear to be having has to do with the unserialize() function.
Here is the output I am getting:
html
php
You are given a set of four checkboxes which you click and press submit. The information is supposed to be written to the database (which it does) and then retrieved and printed to the screen. The problem I appear to be having has to do with the unserialize() function.
Here is the output I am getting:
and here is my code:doQuery = Resource id #6...Array.........
Warning: Invalid argument supplied for foreach() in /home/a5317204/public_html/myTestDir/colorTest.php on line 28
...Array.........
Warning: Invalid argument supplied for foreach() in /home/a5317204/public_html/myTestDir/colorTest.php on line 28
...Array.........
Warning: Invalid argument supplied for foreach() in /home/a5317204/public_html/myTestDir/colorTest.php on line 28
...Array.........
Warning: Invalid argument supplied for foreach() in /home/a5317204/public_html/myTestDir/colorTest.php on line 28
html
Code: Select all
<form method="post" action="colorTest.php">
<input type="checkbox" id="colors[]" value="red" /> Red
<input type="checkbox" id="colors[]" value="blue" /> Blue
<input type="checkbox" id="colors[]" value="green" /> Green
<input type="checkbox" id="colors[]" value="yellow" /> Yellow
<input type="submit">
</form>Code: Select all
<?php
$username="user";
$password="pass";
$database="dbt";
@mysql_connect(localhost,$username,$password) or die("Unable to connect.");
@mysql_select_db($database) or die( "Unable to select database.");
$colors=serialize($_POST['colors']); //takes the data from a post operation...
$query="INSERT INTO color VALUES('$colors')";
$doQuery=mysql_query($query);
$query="SELECT * FROM color";
$doQuery=mysql_query($query);
print "doQuery = ".$doQuery;
if($doQuery != null)
$numrows=mysql_num_rows($doQuery);
if($numrows>0)
{
while($colors=mysql_fetch_array($doQuery))
{
print "...".$colors."...";
$colors=unserialize($colors["color"]);
print "...".$colors."...";
foreach($colors as $shirt)
{
print $shirt.', ';
}
}
}
else
{
print 'No colors in database.';
}
?>