Insert A PHP Array in MySQL in one Cell

I’m trying to insert an array in a single string of data (comma separated) into one MYSQL cell. The problem is that only the last name in the array is listed in the database even though the array data string is echoed correctly only the last item (name) appears in the database cell. What am I doing wrong. The code is below:

[php]

foreach($fb_friends as $friends) 
	{
	$friend = ($friends['name']);
	$array = array($friend);
	$comma_separated = implode(",", $array);
	echo $comma_separated;
	require 'connect.php';
	$query = "UPDATE `3` SET A='$comma_separated' WHERE id=1";
	$query_run = mysql_query($query);
	}[/php]

Hi,

looks like you have a bit of a scope problem.
Every time the loop passes over the :
[php]$array = array($friend);
[/php]
You create a beautiful new array with only one friend in it.
I doubt the data string is ‘echoed correctly’, you see all your friends because of the loop. But you all see them once (right?). If it were correct you’d see:

Friend1Friend1,Friend2Friend1,Friend2,Friend3Friend1,Friend2,Friend3,Friend4... (&c.)
What you should do is take the array-creation out of the loop, like this:
[php]$array = array(); // If you declare it here it won’t be emptied by a new declaration
foreach($fb_friends as $friends)
{ $friend = ($friends[‘name’]);
$array[] = $friend; // This translates to “Stick $friend to the end of $array”
$comma_separated = implode(",", $array);
echo $comma_separated;
require ‘connect.php’;
$query = “UPDATE 3 SET A=’$comma_separated’ WHERE id=1”;
$query_run = mysql_query($query);
}[/php]
Now I doubt you want to shoot off the query inside the loop, it’d mean you’d run the query for every friend. You’d probably foul up your database that way, so you take that out of the loop too:
[php]$array = array(); // If you declare it here it won’t be emptied by a new declaration
foreach($fb_friends as $friends)
{ $friend = ($friends[‘name’]);
$array[] = $friend; // This translates to “Stick $friend to the end of $array”
}
$comma_separated = implode(",", $array); // You do this once, on the finished array
echo $comma_separated; // That should reduce the noise on your screen too.
require ‘connect.php’;
$query = “UPDATE 3 SET A=’$comma_separated’ WHERE id=1”;
$query_run = mysql_query($query);
[/php]

I hope I explained a little what gave you the rather unexpected result.
Good luck.

O.

Thank you so much! I’m going to give this a try tomorrow! I spent days trying to figure this out!

Ojoshiro It worked!!! Thank you so much!! I’ve worked on this for weeks!!!

Sponsor our Newsletter | Privacy Policy | Terms of Service