Question

PHP storing a two dimensional array in a database

Asked by: allanch08

Hello experts,

This is my first foray into multidimensional arrays. Can someone tell me what is the best way to store values in a multidimensional an array in a database. For single arrays I use 'implode' and save as a string and if I need to access the values I use 'explode'. Can this be done for multidimensional arrays and is this the best way of doing it or do I need to use 'serialize'? I've enclosed a snippet of the code I've started. Thanks

$user_id = 00001;
$note = 'Hello world';
 
// Create array.
$message = array(array(''.$user_id.'', ''.$note.''));				
 
foreach ($message as $key) {
	foreach ($key as $key1=>$value) {
		echo $value;
	}
}
 
// Result
00001Hello world

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-05 at 15:27:11ID24787252
Tags

PHP

,

MYSQL

Topics

PHP Scripting Language

,

PHP and Databases

Participating Experts
3
Points
500
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. I need PL/SQL implode and explode functions
    I get this request often when running reports. Let's say I am to create a report that lists servers and their IP addresses. If there is more than one IP Address for a given server, I need them to be comma delimited in a single field. So, in this case, I would like to write a...
  2. explode
    i'm inserting the value into my db, but i would like the name of the field to be pass in the e-mail would i use explode for this? <input type="checkbox" value="1" name="exterior[]">Front Bumper
  3. Array explode and implode
    I have a variable $names="steve, john, mark" I do this $name_array=explode(",",$names); How can I now implode the array so that I can include it in an SQL statement like this select * from database where name!='steve' and name!='john' and name!='mark'...
  4. exploding at line break and imploding back into values
    I need help with two things here. I have: $sample="sample 1 sample 2 sample 3"; I need to explode that at the line break, how do I write that? $sample_array=explode ('what here?', $sample); Then, I little trickier I think, I need to implode it back together wh...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: 930913Posted on 2009-10-05 at 15:40:45ID: 25500520

You can nest two for loops each one counting a dimension serialising it as you said.
As long as it is read back in the same way, it doesn't matter how you save it.

 

by: Ray_PaseurPosted on 2009-10-05 at 16:03:06ID: 25500663

I think you can just serialize() the array.  See the notes on the man page here:
http://us2.php.net/serialize

Be sure to escape the serialized data before inserting it - use mysql_real_escape_string() or the equivalent for your DB.

Best, ~Ray

 

by: cxrPosted on 2009-10-05 at 16:13:23ID: 25500733

>> what is the best way to store values in a multidimensional an array in a database

The best way is to store it in columns in a table:

create table Messages (userid int,note text);

You should probably have some additional columns, maybe a timestamp? If each user can have only one note, you should have an index on the userid column.

 

by: allanch08Posted on 2009-10-05 at 22:47:20ID: 25502124

thanks for the help everyone.

I've set it up so the user can have multiple notes, say maximum of 10 that they can add/remove from. The table has two columns - user_id, note. 'user_id' is unique int, while 'note' is text and contains all values of the array.

I will do some reading on serialize and give it a try and get back with results

 

by: allanch08Posted on 2009-10-05 at 22:50:00ID: 25502135

'As long as it is read back in the same way, it doesn't matter how you save it.' is a very good point that I will work on too

 

by: Ray_PaseurPosted on 2009-10-06 at 04:29:17ID: 25503793

@allanch08: You may be asking a "loaded" question here.  If you have only a small amount of data and you do not need to search it, almost any factually correct answer about how to store it will be acceptable.  By "small amount" I am thinking a few thousand records a day at most.  However if you need the data base capabilities, then you want to think about the structure of the data and in that case, serialize() is maybe not the best approach, since serialize() removes the structure and converts it into a string (albeit a reversable process).  If the underlying question is deeper than what you've posted here, consider "normalization."
http://lmgtfy.com?q=why+should+i+normalize+my+database

Best, ~Ray

 

by: allanch08Posted on 2009-10-06 at 05:50:49ID: 25504377

thanks ray. It's just a small amount of data I'm working with, I thought about using tables in a db but that would be too much for it. This is the code I've got so far and it prints out:

0 = 00001Hello1 = 00002Goodbye2 = 00005Good morning3 = 00007Good evening

I understand that there are three numeric keys [1][2][3] with corresponding values and this is a big string but how can I format it so I can change it back into an array?  

$message = array(
 
array('user_id' => '00001', '$msg' => 'Hello'),
array('user_id' => '00002', '$msg' => 'Goodbye'),
array('user_id' => '00005', '$msg' => 'Good morning'),
array('user_id' => '00007', '$msg' => 'Good evening'));
 
foreach ($message as $key => $value) {
	$fav .= ''.$key.' = ';
	foreach ($value as $id => $value1) {
		$fav .= ''.$value1.'';
	}
}
 
echo $fav;
 
 
0 = 00001Hello1 = 00002Goodbye2 = 00005Good morning3 = 00007Good evening

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: Ray_PaseurPosted on 2009-10-06 at 06:08:36ID: 25504529

Run this, look at the code and output together, and see if it helps clarify what happens here.  Please post back with any questions.  Best regards, ~Ray

<?php // RAY_serialize_unserialize.php
error_reporting(E_ALL);
echo "<pre>\n"; // READABILITY
 
// TEST DATA FROM THE OP
$message = array(
   array('user_id' => '00001', '$msg' => 'Hello'),
   array('user_id' => '00002', '$msg' => 'Goodbye'),
   array('user_id' => '00005', '$msg' => 'Good morning'),
   array('user_id' => '00007', '$msg' => 'Good evening'),
);
 
// SHOW THE INITIAL ARRAY
var_dump($message);
 
// CONVERT THE DATA FORMAT
$s = serialize($message);
echo "SERIALIZED:";
var_dump($s);
 
// ESCAPE THE DATA - IN THE REAL SCRIPT, USE mysql_real_escape_string() INSTEAD OF addslashes()
$e = addslashes($s);
echo "ESCAPED:";
var_dump($e);
 
// UNESCAPE THE DATA - IN THE REAL SCRIPT, THIS HAPPENS WHEN THE DATA GETS INSERTED INTO THE DB
$u = stripslashes($e);
echo "UNESCAPED:";
var_dump($u);
 
// CONVERT SERIAL DATA BACK
$new = unserialize($s);
var_dump($new);
 
// COMPARE
if ($message === $new) echo "\nEQUAL!";

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: allanch08Posted on 2009-10-06 at 08:55:24ID: 25506489

thanks ray that code is really helpful. I'm going to study it a bit more. one thing I stumbled upon when learning more about serialize was in this blog:

http://davidwalsh.name/php-serialize-unserialize-issues

any views on this? thanks

 

by: Ray_PaseurPosted on 2009-10-06 at 09:06:52ID: 25506636

Yes - the use of base64encode() changes the length.  You might want to be careful of this since MySQL is length-aware for certain data types (VARCHAR, for example) and may truncate the data.  Other than that, it looks like a good idea.

 

by: cxrPosted on 2009-10-06 at 10:45:50ID: 25507693

There is no known bug in unserialize(), the problem described at the blog mentioned above was probably because magic_quotes was enabled, so that addslashes() (or mysql_real_escape_string()) was called twice. There is no problem using the characters ', ", ; or : (or any other characters) in array values when using serialize()/unserialize().

 

by: allanch08Posted on 2009-10-07 at 06:05:32ID: 25514867

thanks, I did notice that using base64encode did generate a lot of characters. I also been testing serialize/unserialize and all works. another question is have is how can i refer to associative keys. to explain better in the code below the varialbe '$note' has two values for each array. so how can i just print the 'user_id' in each case? thanks

<?php
 
$message = array(
   array('user_id' => '00001', '$msg' => 'Hello'),
   array('user_id' => '00002', '$msg' => 'Goodbye'),
   array('user_id' => '00005', '$msg' => 'Good morning'),
   array('user_id' => '00007', '$msg' => 'Good evening'),
);
 
 
// Loop through and print all entries.
foreach ($message as $key => $key1) {
	foreach ($key1 as $id => $note) {
		echo ''.$note.'<br />';
	}
} ?>
 
//Results.
00001
Hello
00002
Goodbye
00005
Good morning
00007
Good evening

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

Select allOpen in new window

 

by: allanch08Posted on 2009-10-07 at 06:30:42ID: 25515081

sorry mistake in code.

managed to echo  a specific element using

echo '$message[0]['msg']';

would give 'Hello'

<?php
 
$message = array(
   array('user_id' => '00001', 'msg' => 'Hello'),
   array('user_id' => '00002', 'msg' => 'Goodbye'),
   array('user_id' => '00005', 'msg' => 'Good morning'),
   array('user_id' => '00007', 'msg' => 'Good evening'),
);
 
 
// Loop through and print all entries.
foreach ($message as $key => $key1) {
	foreach ($key1 as $id => $note) {
		echo ''.$note.'<br />';
	}
} ?>
 
//Results.
00001
Hello
00002
Goodbye
00005
Good morning
00007
Good evening
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

Select allOpen in new window

 

by: cxrPosted on 2009-10-07 at 09:23:18ID: 25517131

Try like this:

foreach ($message as $msg) {
    echo $msg['user_id'].' '.$msg['msg'].'<br />';
}

                                              
1:
2:
3:

Select allOpen in new window

 

by: allanch08Posted on 2009-10-08 at 00:49:28ID: 25522947

that worked, thanks!

 

by: allanch08Posted on 2009-10-08 at 01:00:56ID: 25523002

what I managed to assign the user_id name to the array, I guess the danger in this is duplicate user_id will result in duplicate keys which is not nice

$message = array(
   '00001' => array('msg' => 'Hello'),
   '00002' => array('msg' => 'Goodbye'),
   '00005' => array('msg' => 'Good morning'),
   '00007' => array('msg' => 'Good evening'),
);
 
foreach ($message as $key => $key1) {
	echo $key;
	foreach ($key1 as $id => $note) {
		echo ' msg = '.$note.'<br /><br />';
	}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: cxrPosted on 2009-10-08 at 03:09:52ID: 25523601

>> duplicate user_id will result in duplicate keys

PHP prevents duplicate keys, the last assigned array will overwrite the previous with the same key.

 

by: allanch08Posted on 2009-10-08 at 04:05:42ID: 25523956

cool so there is no real problem in the way that I did it either?

 

by: cxrPosted on 2009-10-08 at 06:06:35ID: 25524889

No, except if you have multiple messages for the same user. Then only the last one will be stored. This is not the case with how you did it earlier: array('user_id'=>1,'msg'=>'Hello') In this case there can be multiple messages for the same user id.

 

by: allanch08Posted on 2009-10-08 at 06:21:20ID: 25525026

okay, thanks for help always appreciated!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...