Jump to content

unserialize()


jamkelvl

Recommended Posts

I have a form with a bunch of checkboxes.

 

Lets say, 3 boxes are checked and the form is submitted.

 

The values of those checkboxes are captured via

<?php $assignedTo = serialize($_POST['assignedTo']); ?>

 

and then posted to the database.  The result is something like this:

 

a:3:{i:0;s:7:"Stephen";i:1;s:6:"Suhail";i:2;s:6:"Warren";}

 

I want to either properly use the unserialize() function when displaying this information.  Or maybe use the str_replace() function (probably not a good idea).  Keep in mind, the unserialize() function will be used on a different page.  Is this possible?

 

The other page just displays all records from the database in a table.

 

Worst case scenario, I want to use str_replace() to break up the string and remove as many useless characters as possible... something like:

<?php
// No numbers or symbols
$apattern = '([[:digit:]]|[~`!@#$%^&*()_=+{}|\:;"/?,]|[|]|-)+';
?>

 

Any help?

Link to comment
Share on other sites

i just grab the array from the database and then unserialze it. which puts it in a nice array here is a code snip from my current project.

 

 

$q2 = mysql_query("SELECT montrack FROM dbase0.table0 where username='nonuser10'")

or die(mysql_error()); 

$row3 = mysql_fetch_row($q2);

$db_arr0 = $row3[0];

$arr_unser = unserialize($db_arr0);

$plode = explode(":",$arr_unser[0]);

Link to comment
Share on other sites

Hmm...

 

I'm not the greatest programmer and wasn't able to make unserialize() work myself.

 

Since then I've created a bandaid:

 

<?php 
// vars
$search = array(':', '{', ';', '"', '}');
$replace  = array(' ', ' ', ' ', ' ', ' ');
$assignedTo = str_replace($search, $replace, $assigned_to);
?>

 

Think you could break down that code to something more simple?  Sorry I'm a noob and my brain is fried.

Link to comment
Share on other sites

1. Yes I did serialize.

 

2. I don't know if can select an array in the DB, I'm new and never done it before.  How do I begin?

 

3. I probably can unserialize, just never have used this function and have yet to do it successfully,.

 

By the way, thank-you.  So far, very helpful :)

 

Link to comment
Share on other sites

1. Yes I did serialize.

 

2. I don't know if can select an array in the DB, I'm new and never done it before.  How do I begin?

 

3. I probably can unserialize, just never have used this function and have yet to do it successfully,.

 

By the way, thank-you.  So far, very helpful :)

 

Why not test something simple out?

//Define array to serialize
$var[0] = 'hello';
$var[1] = 2;
$var[2] = PHP_EOL;

$vars = serialize($var); //a:3:{i:0;s:5:"hello";i:1;i:2;i:2;s:2:" ";}
echo "<pre>"; //Formatting for print_r;
$newarray = unserialize($vars);
echo print_r($newarray); //show what the unserialized result is.

 

Which returns:

Array
(
    [0] => hello
    [1] => 2
    [2] => 

)

 

It'd be useful to read up on serialize before implementing it. You should always read methods and their possible security problems.

Link to comment
Share on other sites

I didn't know i was dealing with a junior programmer........I serialize an array before putting it in a database because its about the only way to store an array in a db.....in my opinion this is about the only use for serialize. something to put in your toolbox for future use.

Link to comment
Share on other sites

Good idea, I've thought of that before, only I could not get the unserialize function to work.

 

Now I have a better understanding, how would I insert the unserialized array into my database?

 

<?php
                          // all other code omitted
		// If user is trying to add new record
		if ($addNew == true) {
			// Capture form data				
		           $assignedTo = serialize($_POST['assignedTo']);													
			   $newAssignedTo = unserialize($assignedTo);							

						// Build query
						$insert = "insert into customers values ('$id', '$shipTo', '$unitNumber', '$tenantName', '$tenantNumber', '$workOrderNumber', '$dateRequested', '$hours', '$minutes', '$time', '$eMailVerbal', '$startDate', '$scheduledDate', '$jobDescription', '$jobCompleted', '$serviceCharge', '$newAssignedTo[0]', '$invoiceNumber', '$invoiceDate', '$total', '$dateSentIn', '$paidDate', '$EFTNumber')";
						$result = mysql_query($insert);

//blah blah blah
?>

Link to comment
Share on other sites

$conn = mysql_connect("127.0.0.1", "root", "mypass") or die(mysql_error());

mysql_select_db("mydb",$conn) or die(mysql_error());

 

$arr_unser = array();

$arr_unser[0]="data0";

$arr_unser[1]="data1";

$arr_unser[2]="data2";

$arr_ser = serialize($arr_unser);

$q = mysql_query("insert into mydb.mytable (field0) values('$arr_ser') ")

or die(mysql_error());

 

 

first put your data in the array then store it in database.

Link to comment
Share on other sites

Correct me if I'm wrong but won't that just put "Array" into the database?

 

Okay, after reading over this again, I've seen that you said you serialize before storing an array in database.  Originally that is what I did.

 

Now, on a seperate page, I want to unserialize the array (I now know how to do this).

 

Here is my new problem:

 

I want to display the array inside of a table.. the table is dynamically created in a while loop.

 

Is it possible to add a foreach loop in the while loop?

 

Something like:

 

<?php
                                                        //vars
                                                        $x = 0;
  							// get results
						while($row = mysql_fetch_array($result)){
							extract($row);	
                                                                // unserialize
							$newAssignedTo[$x] = unserialize($assigned_to);	
                                                                $x++;			
							echo 
							'<tr>
								<td class="view" width="49px">'.$id.'</td>
								<td class="view" width="128px;">'.$ship_to.'</td>
								<td class="view" width="76px">'.$unit_number.'</td>
								<td class="view" width="250px">'.$job_description.'</td>
								<td class="view" width="64px">'.$job_completed.'</td>					
								<td class="view" width="65px">'.$work_order_number.'</td>
                                                                          // below i want the unserialized array displayed... something like
                                                                          //    Mike, Steve, Joe
								<td class="view" width="86px">'.$assigned_to.'</td> 
								<td class="view" width="49px">'.$invoice_number.'</td>
								<td class="view" width="81px">'.$invoice_date.'</td>
								<td class="view" width="78px">'.$total.'</td>					
								<td class="view" width="79px">'.$date_sent_in.'</td>
								<td class="view" width="79px">'.$paid_date.'</td>
								<td class="view" width="80px">'.$eft_number.'</td>	
								<td class="view" width=""><a href="edit.php?recordID='.$id.'">view</a> delete</td>
							</tr>';	
						}
?>

 

I believe this is possible, probably a few ways to go about it.  I could instead... in theory, loop through the new unserialized array, take everything and store it in a variable as one string?  Then display the string?

 

Ugh... no idea where I'm going with this... just typing and thinking out loud?

 

Maybe my bandaid would suffice, if only I could search for something like

 

<?php
     $assignedTo = "a i s Billy i s Mark is Steve...";
     $search = array ('a i s', 'i s');
     $replace = array (' ', ', ');
     $newString = str_replace($search, $replace, $assignedTo);

Link to comment
Share on other sites

Correct me if I'm wrong but won't that just put "Array" into the database?

 

He's serializing it. Why do you want to shove an array in the database that is unformatted? You'd break the array up or assign a pointer to each one,.

Link to comment
Share on other sites

I apologize for my failure.

 

I have created a solution, I've put a solid 40+ hours into this in the past 4 days, i'm fried.  Not to mention I'm a full-time student and working on this, it's also my birthday  :D

 

Anyways, here goes:

 

<?php
						// query database
						$select = "SELECT * FROM customers ORDER BY id";
						$result = mysql_query($select);		

						//fix string
						$search = array(':', ';', '{', '}', '"', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
						$replace = array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
						$searchAgain = array('ais', 'is');
						$replaceAgain = array('', ', ');
					?>
					<?php				
						// get results
						while($row = mysql_fetch_array($result)){
							extract($row);								
							$newAssignedTo = str_replace($search, $replace, $assigned_to);
							$finalAssignedTo = str_replace($searchAgain, $replaceAgain, $newAssignedTo);																				
							echo 
							'<tr>
								<td class="view" width="49px">'.$id.'</td>
								<td class="view" width="128px;">'.$ship_to.'</td>
								<td class="view" width="76px">'.$unit_number.'</td>
								<td class="view" width="250px">'.$job_description.'</td>
								<td class="view" width="64px">'.$job_completed.'</td>					
								<td class="view" width="65px">'.$work_order_number.'</td>
								<td class="view" width="86px">'.$finalAssignedTo.'</td>
								<td class="view" width="49px">'.$invoice_number.'</td>
								<td class="view" width="81px">'.$invoice_date.'</td>
								<td class="view" width="78px">'.$total.'</td>					
								<td class="view" width="79px">'.$date_sent_in.'</td>
								<td class="view" width="79px">'.$paid_date.'</td>
								<td class="view" width="80px">'.$eft_number.'</td>	
								<td class="view" width=""><a href="edit.php?recordID='.$id.'">view</a> delete</td>
							</tr>';	
						}					
						mysql_close($connection);	
					?>

Link to comment
Share on other sites

This page displays all records in the database.

 

In the "Assigned To" field on the page (it's a table).  I want to display all employees who have been assigned to the job (it's for a small contracting company).

 

That said, no.  I do not think I can do that, nor want to do that as I am fried and have a bandaid solution.

 

Thank-you very very much for you help kind sir.  You deserve a pat on the back for watching my thread.  And thank-you to anyone else who has looked at this.  I think I've had so much trouble as my roommates are partying and the guy I'm writing this for is drunk and swaying back and fourth behind me barking in my ear.  Lol, sorry!  College life, rofl.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.