user652792
user652792

Reputation:

How to display multiple rows of comma separated values from mysql db

I need your help with display of some comma separated enteries from my database.

My main table schema looks like this

              |---|----------|-----------|----------------------------|
              |id | tab1     |  tab2     |          tab3              | 
              |---|----------|-----------|----------------------------|
              |1  |  state1  |  A-North  |   constA1,constA2,constA3  |
              |2  |  state2  |  B-South  |   constB1,constB2,constB3  |
              ---------------------------------------------------------

Query I'm trying to make work

$query = mysql_query("SELECT * FROM `main` WHERE `tab1` = '$tab1'") 
         or die(mysql_error());

while($row=mysql_fetch_array($query)){                  
  $tab3 = explode(",", $row['tab3']);
  echo $tab3."<br>";
}       

What I want to display from the database

               A-North      B-South
               ---------------------                   
               constA1      constB1
               constA2      constB2
               constA3      constB3

Error I'm getting when I run that query is "Array" . When I run the same code from phpMyAdmin, I get the desired rows (result).

Upvotes: 0

Views: 3769

Answers (3)

Miqdad Ali
Miqdad Ali

Reputation: 6147

explode will return array using print_r($tab3) you can view the items and access it by

echo $tab[0];
echo $tab[1];
echo $tab[2];

etc.....

Upvotes: 1

DaveyBoy
DaveyBoy

Reputation: 2915

explode ($separator,$string) returns an array. You need to step through the array to create the table columns.

Also, as you want the data in two columns, create these separately as two separate tables and then include those into a single table as two separate cells

Finally, redesign your database table. You'll thank us in the end

Upvotes: 0

SpaceBeers
SpaceBeers

Reputation: 13947

Explode gives you the results in an array so you'll want another loop that runs through the $tab3 array printing the result. See the definition from the PHP manual:

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

For example:

for ($i = 0; $i < sizeof($tab3); $i++) {
    echo $tab3[$i].'<br />';
}

Upvotes: 4

Related Questions