1

I have a table with column names id, name, category, title,and news. Once select query executes I get all the required data from table but i need to split up this data into two div according to the category they belong. there are two different categories, say A and B.

I need to show all the data with a column category name A in one div and same with category B.

$sql= "SELECT id, title ,news ,category FROM news  ";
$query=mysql_query($sql, $ex)or die(mysql_error())  ;
while($row=mysql_fetch_assoc($query)){ 
    $title=$row['title']; 
    if($row['category']==' Latest News'){
        echo $row['title'];
    }
}

My code doesn't work. Any idea?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
munna ss
  • 194
  • 1
  • 2
  • 11
  • `$query=mysql_query($sql, $ex)` _deprecated_ mysql functions. `echo $title=$row['title']; ` does this work? _If_ so, then comes the strict comparison excluding the white-space ofcourse – DirtyBit Oct 04 '15 at 08:28
  • Show sample data, and more code. I see no attempt at distributing the data over the divs. – Jan Doggen Oct 04 '15 at 08:35

1 Answers1

1

You can first separate out category wise data into separate arrays.

$cat1 = array();
$cat2 = array();

$sql= "SELECT id, title, news, category FROM news";

$query = mysql_query($sql, $ex) or die(mysql_error());

if(mysql_num_rows($query) > 0)
{
    while($row = mysql_fetch_assoc($query))
    { 

        if($row['category'] == 'A')
        {
            $cat['title'] = $row['title'];
            $cat['news'] = $row['news'];
            $cat1[] = $cat;
        }
        else
        {
            $cat['title'] = $row['title'];
            $cat['news'] = $row['news'];
            $cat2[] = $cat;
        }

    }
}

Then you can use foreach to print the data into separate div

if(count($cat1) > 0)
{
    foreach($cat1 as $category1_data)
    {
    echo "<div class='cat1'>";
    // data of category A
    echo "</div>";
    }
}

if(count($cat2) > 0)
{
    foreach($cat2 as $category2_data)
    {
        echo "<div class='cat2'>";
        // data of category B
        echo "</div>";
    }
}
Suyog
  • 2,472
  • 1
  • 14
  • 27