PHP storing array in database?

  • Thread starter Thread starter ryansmith9lz
  • Start date Start date
R

ryansmith9lz

Guest
From what im aware there is no direct way to store an array in a MySQL database. Maybe im wrong?

What methods are there for storing arrays?

Only thing i can think of is a string seperated by say a + etc..

Any code???
 
doesn't the database act as a placeholder for your array? Can't you just cycle through your array and store each entry as a string? Then, when you need the info back you read the column and store the entries as an array.
 
I'm going to assume this is a single dimensional array.

lets say you have the following values in an array: data1, data2, data3

Here's a code snippet of how I would handle the array and store them into MySQL:

<?php

//database connect string to be used later
$dbhost = "localhost";
$dbname = "database_name";
$dbuser = "username";
$dbpass = "password";

$connect = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $connect);

$a=array("data1","data2","data3")

//You can use foreach to separate the data elements.

foreach ($a as $value) {
//now data element is contained within the variable $value
//at this point you could echo $value to screen or insert into
//database, I'll do both.

//record insert into database
$sql="INSERT into TABLE values ('$value')";
$res=mysql_query($sql);

// output $value to screen
echo $value."\n";

//loop through the array until all values have been accounted for
}

?>
 
Back
Top