3

Ok basically I can't figure out how to get the imploded result from mysql back to a usable variable in php. The array is throwing me for a loop, and driving me nuts.

The checkboxes that are being dynamically created from the db:

<input name="tournament_id[]" value="'.$row['tournament_id'].'" type="checkbox">'.$row['tournament_name'].'

The posted value getting imploded (no sql injection prevention implemented yet):

$got_tournament_id = implode(",",$_POST['tournament_id']);

This gets inserted into mysql like this:

id   user_id   tournament_id
1    16942627  1,10

This is my mysql query to grab the imploded data:

$query = ("SELECT tournament_id FROM tournament WHERE user_id=16942627");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$got_it = $row['tournament_id'];    
}
$bust_him = var_dump(explode(",", $got_it));
echo $bust_him;

The above using var_dump is returning the following:

array(2) { [0]=> string(1) "1" [1]=> string(2) "10" }

Now this is where I am totally lost, and can't figure out what to do to get the values 1 and 10 from the array into individual variables. I have tried several ways to do it and I keep ending up with errors, or just the word array. I need some help if anybody can give some. Thanks in advance.

Rich Adams
  • 26,096
  • 4
  • 39
  • 62
BeKustom
  • 47
  • 2
  • 10

1 Answers1

7

Don't var_dump(), whose purpose is debugging, not code or display logic. Just store the output of explode() into $bust_him (what a weird variable name):

// Store the output of explode() directly
$bust_him = explode(",", $got_it);
// No need for individual variables, just access via array keys.
echo $bust_him[0];
echo $bust_him[1];
// etc...

If you have a fixed number of elements, you can use list() to place into variables:

// You know you only have two, so you can use list()
// to store directly into variables
list($first, $second) = explode(",", $got_it);
echo $first;
echo $second;

In the long run, a better solution than storing comma-separated values in your table is to create a separate, properly normalized table which links tournament_id to user_id. You then have multiple rows per user_id, each containing one tournament_id. This makes for much simpler and more efficient querying in a lot of instances, enabling the use of COUNT() aggregates for example, among many other benefits.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Thanks for the point in the right direction there. I was all around the answer just not quite right, but again thank you. Also I thought about redoing what I have, and implementing what you mentioned about the normalized table as I think this would be better in the long run. Once again thank you for the quick answer. – BeKustom Jul 24 '12 at 15:28