-2

I have a column in my table that contain an array like:

1,4,2,8,4,5,7

How to select these numbers and print them separately?

Item: 1
Item: 4
Item: 2
Item: 8
Item: 4
Item: 5
Item: 7

What I have tried:

$result = mysql_query('SELECT * FROM test');

$arr = array();

while(($row = mysql_fetch_array($result))) {
    $arr = array_merge($arr , explode(',', $row['item']));
    echo "Item: " . $arr . "<br>";
}

Result:

Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array

Can anyone help me?

Kelson Batista
  • 406
  • 4
  • 25
  • you are basically echoing an array (`$arr = array() ===> echo $arr)`, so maybe start over? – arnoudhgz Feb 17 '15 at 18:12
  • Don't use mysql functions, use either `mysqli` or `PDO` for database queries. [Here is a good link why.](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – kidA Feb 17 '15 at 18:14

3 Answers3

2

Your biggest problem is trying to echo the whole array at once rather than echoing an index of the array at a time.

Unless you plan on using all the rows again after the while loop, you don't need the array_merge so take that out. What you need is a foreach inside the while loop to loop through the array created by explode.

while(($row = mysql_fetch_array($result))) 
{
    $arr = explode(',', $row['item']);
    foreach ($arr as $key => $value)
    {
       echo "Item [$key]: " . $value . "<br>";
    }
}

(And you really should switch off of mysql_ to PDO or mysqli_ since mysql_ is deprecated.)

developerwjk
  • 8,619
  • 2
  • 17
  • 33
0

try:

$arr = explode(',', $row['item']);
foreach($arr as $single){
  echo "item: $single";
}
xam
  • 452
  • 2
  • 7
  • 15
0

You are almost there. I hope this gives the result you expect. In your question it is not quite clear how exactly the data is stored.

If all the data is in one row, this will do it:

$result = mysql_query('SELECT item  FROM test');
$arr = array(); 
$row = mysql_fetch_array($result);
$arr = explode(',', $row['item']);
foreach ($arr as $item) {
    echo "Item: " . $item . "<br>";
}
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121