How to unserialize from a mySQL Database

I have a checkbox value which I store in a mySQL database serialized. However, I’m having a problem displaying the values when pulling them out. Here is my view script:


<?php
        $query = "SELECT * FROM requests";
        $result = mysql_query($query);
        $num = mysql_numrows($result);
        mysql_close($link); 
        
        for ($i = 0; $i < $num; $i++) {
            $date = mysql_result($result,$i,"date");
            $title = mysql_result($result,$i,"title");
            $first = mysql_result($result,$i,"first_name");
            $last = mysql_result($result,$i,"last_name");
            $address = mysql_result($result,$i,"address");
            $city = mysql_result($result,$i,"city");
            $province = mysql_result($result,$i,"province");
            $postal = mysql_result($result,$i,"postal_code");

        echo "<tr><td>$date</td><td>$title</td><td>$first</td><td>$last</td><td>$address</td><td>$city</td><td>$province</td><td>$postal</td><td>$phoneHome</td><td>$phoneOffice</td><td>$email</td><td>$commPref</td><td>$comments</td></tr>";
        } ?>

The one that needs to be unserialized is $title. Any help would be greatly appreciated.

What do you mean by “a checkbox value which I store in a mySQL database serialized” ?
Could you post the code that inserts the record into the database. The problem your describing doesn’t make a whole lot of sense. At least not to me anyway.

$title = unserialized($title);

?

Sure, I insert everything into a database using a simple mySQL function, but the array is serialized by:

$title = serialize($_POST['title']);

what he said, but without the d at the end of the function name :cool:

The problem then becomes that is just comes back as “Array”, instead of the values.

Are you echo()'ing $title, or printing each key? “Array” is an array’s __toString() result.

Just a thought - why are you serialising an array to put into a field?

Heres an idea I want you to consider.

Have another table called ‘titles’.

That table has three columns - ID, RequestID and Title.

For every request, you can have multiple titles right? Hence serialising the array?
So how about having a row for each of those titles in the ‘titles’ table?

That way database functions would be so much more efficient and doable, for example:

//get all titles for request #20:
SELECT Title FROM Titles WHERE RequestID = 20
//get the first title for request with FirstName 'Dave'
SELECT Title FROM Titles INNER JOIN Requests ON Requests.ID = Titles.RequestID WHERE FirstName = 'Dave' LIMIT 1

There are other examples etc - but I just wanted to throw this at you to see what you think. Its a more structured way of approaching multiple values than serialising an array.

Here’s some more information about database normalisation.