Echo'ing MySQL Data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Greenconure
Forum Commoner
Posts: 30
Joined: Mon Jun 16, 2008 8:19 am

Echo'ing MySQL Data

Post by Greenconure »

First of all, I have no trouble connecting to my database and I've done this many times.
My problem comes when I want to echo/print/show data from the database in a certain way.

I have been echoing/showing mysql data with either this code or the following code…

Code: Select all

 
while ($row = mysql_fetch_assoc($result)) {
    echo $row['row1']; //Pretend row1 is A
    echo $row['row2']; //Pretend row2 is B
    echo $row['row3']; //Pretend row3 is C
}
 
Would produce:
ABC
Or the other code I found on php.net:

Code: Select all

 
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";
 
Would produce a table:
| A | B | C |
I want to be able to echo certain rows, not always every part of the row like in the first method but have that, like the second method, apply to every column of data and have the ability have a prefix and suffix, such as <span> and </span>

Any ideas? (Please mention if I haven't explained myself well enough - it's a bit hard for me to explain although I know it's fairly simple)
<br>
Forum Commoner
Posts: 35
Joined: Thu May 01, 2008 2:42 pm

Re: Echo'ing MySQL Data

Post by <br> »

Maybe this code will work for you...

Code: Select all

$column=1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($column==1)//opens a row when counter starts or is reset at 5
    {
    echo '<tr>';
    }
if ($column==2)//Display chosen column in a span
    {
    echo '<span class="myclass">';
    }
echo '<TD>';
echo $row['anyrow'];
echo '</TD>';
if ($column==2)//close the span
    {
    echo '</span>';
    }
$column++;
if ($column==5)//closes row after 4 <TD>s
    {
    echo "</tr>";
    $column=1;
    }
}
 
//add extra <TD>s if it doesn't end on a multiple of 4
if ($column==4)
{
    echo"<TD></TD></TR>";
} else if ($column==3) {
    echo"<TD></TD><TD></TD></TR>";
} else if ($column==2) {
    echo"<TD></TD><TD></TD><TD></TD></TR>";
}
}
Post Reply