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:
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
<?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.';
}
?>
The quick answer is - simply don't put serialized data into DB. There might be some cases where it could be a better way to do it, but in most cases you'll have to create additional tables and put separate record for every array item in them.
There are 10 types of people in this world, those who understand binary and those who don't