Sometimes it’s just impossible to create a functional website without needing to store arrays into a database. Traditionally, the implode() and explode() php methods can work wonders. What about inserting a multidimensional array into a MySQL database using php though? I could’ve gone without doing it, but in trying to be as efficient with queries as possible I found the need to do it for this project.
My form code looked like the following (my backend php stripped out):
<p><label><input name="checkbox[10]" value="15" type="checkbox">Gas Fireplace</label></p> <p><label><input name="checkbox[15]" value="10" type="checkbox">Wood Fireplace</label></p>
This would output an array like this:
[10]=>15 [15]=>10
If you were to simply insert the array as follows, you’d only get the word Array in there:
<? mysql_query("INSERT INTO database (key) VALUES ('".$_POST["checkbox"]."')"); ?>
However, by serializing the data first. You get something much more complex:
<? mysql_query("INSERT INTO database (key) VALUES ('".serialize($_POST["checkbox"])."')"); ?>
Instead of getting the word Array, you’ll get something more like this:
a:56:{i:9;s:8:"cable tv";i:47;s:0:"";i:10;s:0:"";i:15;s:0:"";i:27;s:0:"";i:37;s:0:"";i:36;s:0:"";i:3;s:0:"";i:32;s:0:"";i:6;s:12:"only outside";i:35;s:0:"";i:26;s:0:"";i:34;s:0:"";i:16;s:0:"";i:8;s:0:"";i:48;s:0:"";i:24;s:0:"";i:11;s:0:"";i:25;s:0:"";i:22;s:0:"";i:17;s:0:"";i:50;s:0:"";i:4;s:0:"";i:18;s:0:"";i:49;s:0:"";i:13;s:0:"";i:20;s:0:"";i:12;s:0:"";i:14;s:0:"";i:21;s:0:"";i:19;s:0:"";i:23;s:0:"";i:7;s:0:"";i:46;s:0:"";i:40;s:0:"";i:42;s:0:"";i:38;s:0:"";i:45;s:0:"";i:44;s:0:"";i:43;s:0:"";i:41;s:0:"";i:39;s:0:"";i:1;s:0:"";i:2;s:15:"only small dogs";i:51;s:0:"";i:52;s:0:"";i:53;s:0:"";i:54;s:0:"";i:58;s:0:"";i:57;s:0:"";i:55;s:0:"";i:56;s:0:"";i:28;s:0:"";i:30;s:0:"";i:29;s:0:"";i:31;s:0:"";}
All you have to do now is simply unserialize the database results and poof, you just put your multidimensional array into your MySQL table using PHP
<? $result=mysql_query("SELECT key FROM database LIMIT 1");
$row=mysql_fetch_row($result);
print_r(unserialize($row[0])); ?>
Good luck and happy coding
Tags: arrays, arrays in mysql, multidemsional arrays, mysql, mysql array, php, programming, queries, sql


