尝试使用PHP脚本的CSS更改表中替代行的颜色。我有颜色,但是脚本中的线条重复出现。有没有办法解决?

PHP脚本:

<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

//print_r(PDO::getAvailableDrivers());

$config['db'] = array( //This is the config array with the database details
    'host'              => 'localhost',
    'username'          => 'root',
    'password'          => '',
    'dbname'            => 'website'
);


//echo '<table, th, td {border: 2px solid black; border-collapse="collapse";} >';
echo '<table id="customers"}>';
echo '<link rel="stylesheet" type="text/css" href="style.css">';

echo '<th> one </th>';
echo '<th> two </th>';
echo '<th> three </th>';
echo '<th> four </th>';


$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); //Instanciate an PDO Object


$query = $db->query("SELECT `articles`.`title`, `articles`.`hello`, `articles`.`id`,         `articles`.`name` FROM `articles` WHERE `articles`.`title` > 1 LIMIT 5");//running a query         from the database


while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>';
echo $row["title"];
echo '</td>';
echo '<td>';
echo $row["hello"];
echo '</td>';
echo '<td>';
echo $row["id"];
echo '</td>';
echo '<td>';
echo $row["name"];
echo '</td>';
echo '</tr>';
echo '<tr class="alt">';
echo '<td>';
echo $row["title"];
echo '</td>';
echo '<td>';
echo $row["hello"];
echo '</td>';
echo '<td>';
echo $row["id"];
echo '</td>';
echo '<td>';
echo $row["name"];
echo '</td>';
echo '</tr>';

//print_r($query); //printing a query

};

echo '</table>';

echo '<p> Returned ', $query->rowCount(), ' results due to limit set</p>';


//$query = $db->query("SELECT `title` FROM `articles`");//running a query from the database


//$query = $db->query("SELECT * FROM articles");


//print_r($query); //printing a query

//$stmt = $db->prepare($sql);
//$stmt->execute();
//$results = $stmt->fetchAll();

/* $query = $db->query("SELECT `id` FROM `articles`");//running a query from the database

while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['title'], '<br>';
echo $row['id'], '<br>';
}

}

*/


CSS脚本:

#customers
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
#customers td, #customers th
{
font-size:1.2em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#customers th
{
font-size:1.4em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#fff;
}
#customers tr.alt td
{
color:#000;
background-color:#EAF2D3;
}

最佳答案

$alt=0;
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
 if($alt==0){
  echo '<tr>';
  $alt=1;
 }else{
  echo '<tr class="alt">';
  $alt=0;
 }
 echo '<td>';
 echo $row["title"];
 echo '</td>';
 echo '<td>';
 echo $row["hello"];
 echo '</td>';
 echo '<td>';
 echo $row["id"];
 echo '</td>';
 echo '<td>';
 echo $row["name"];
 echo '</td>';
 echo '</tr>';
}


不要在while循环内重复两次行。只需执行一次,然后替换班级分配。

10-01 07:19
查看更多