3

PHP ループに交互の色の行を含めるにはどうすればよいですか?

$num = mysql_num_rows($qPhysician);

$i=0;

while($i < $num)

{

    echo "<tr>";
    echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
    echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
    echo "</tr>";

    $i++;

}

この質問では許可されていないため、「tr」と「td」の両方の「<」と「>」を省略する必要があります。:)

ありがとう!

4

5 に答える 5

10

どう言う意味ですか?行を交互に並べるテーブルにエコーしたいということですか?

$num = mysql_num_rows($qPhysician);
$i=0;
echo "<table>"
while($i < $num)

{
if ($i % 2 == 0){
echo "<tr class='style1'>";
}
else{
echo "<tr class='style2'>";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";

echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";

echo "</tr>";

$i++;

}
echo "</table>";
于 2011-07-17T05:04:00.427 に答える
2

ここで例を続けます:

$query = mysql_query("SELECT lastName, firstName FROM physicians");

$i = 0;
while( $arr = mysql_fetch_assoc( $query ) )
{
    // use modulus (%). It returns the remainder after division.
    // in this case, $i % 2 will be 1 when $i is odd, 0 when even.
    // this is the ternary operator. 
    // it means (if this)? do this: otherwise this        
    // (Remember 1 is true and 0 is false so odd rows will be the odd
    // class, even rows the even class)
    echo ($i % 2)?'<tr class="odd">':'<tr class="even">';
    // Now, use array indexing.
    echo "<td>" . $arr[ "lastName" ] . "</td>";
    echo "<td>" . $arr[ "firstName" ] . "</td>";
    echo "</tr>";
    $i++;
}
于 2011-07-17T05:04:40.947 に答える
0
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$dbname=""; // Database name
$tblname=""; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql="SELECT * FROM $tblname";
$result=mysql_query($sql);
// Define $color=1
$color="1";
echo '<h3 align = "center"> Details <hr /></h3>';
echo '<table width="400" border="1" align="center" cellpadding="2" cellspacing="0">';
while($rows=mysql_fetch_row($result)){
// If $color==1 table row color = #FFCCFF
if($color == 1){
echo "<tr bgcolor='#FFCCFF'><td>$rows[0]</td><td>$rows[1]</td><td>$rows[2]</td><td>$rows[3]</td></tr>";
// Set $color==2, for switching to other color
$color="2";
}
// When $color not equal 1, table row color = #FFC600
else {
echo "<tr bgcolor='#FFC600'><td>$rows[0]</td><td>$rows[1]</td><td>$rows[2]</td><td>$rows[3]</td></tr>";
// Set $color back to 1
$color="1";
}
}
echo '</table>';
mysql_close();
?>
于 2016-04-05T10:31:42.750 に答える
0

あなたが使用できるあなたの中で:

if ($i % 2 == 0)
   echo "even";
else
   echo "odd";
于 2011-07-17T05:01:24.517 に答える