X & Y Marking Table Using Php - php

I'm trying to make an x and y marking table using PHP. I used array and loops to this task.
Please refer to the sample code and image. I almost spent 2hrs finding some solutions still need help.
Very much appreciated for some ideas.
<?php
$x_arr = array();
$y_arr = array();
$n_arr = array();
$x_arr = [5,5,9,14];
$y_arr = [1,4,3,3];
$n_arr = [1,1,1,1];
$x = 16;
$y = 4;
$gap = 3;
$data = "";
?>
<div style="padding:30px; background:#242424;">
<table style="border:20px solid #660000;" align="center">
<?php
//STRIP
for($i=$y; $i>=1; $i--){
?>
<tr style="background:#fff;">
<?php
for($ii=$x; $ii>=1; $ii--){
//echo "<td style='border:1px solid black;'>x".$ii." : y".$i."</td>";
for($iii=0; $iii<=count($x_arr); $iii++){
if(isset($x_arr[$iii]) && isset($y_arr[$iii])){
$x_tmp = $x_arr[$iii];
$y_tmp = $y_arr[$iii];
if($i==$y_tmp && $ii==$x_tmp){
$data= "<td style='border:1px solid black; width:50px; height:30px; text-align:center;'><span data-feather='circle'></span></td>";
echo $data;
}else{
$data = "";
}
}
}
if($data == ""){
echo "<td style='border:1px solid black;'>x".$ii." : y".$i."</td>";
}
//echo "<td style='border:1px solid black;'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</td>";
//echo "<td style='border:1px solid black; width:50px; height:30px; text-align:center;'><span data-feather='circle'></span></td>";
if($ii>$gap){
$gap = $gap+$gap;
}
}
?>
</tr>
<?php
}
?>
</table>
</div>
Result Error :
Current Result
Expected Result :
Target Result

Related

Hide row if field is N/A or empty

I have a question regarding hiding empty rows in my table.
I want to hide an entire row in the case a field says N/A which means the field is empty.
Example:
In the event that the field is empty or N/A, I want to hide the entire row. I will also welcome javascript solutions.
<tbody style="
white-space: nowrap;
">
<?php
foreach($student_subject_list AS $SSL)
{
$subject_name = $SSL["name"];
if(in_array($subject_name, array_keys($result)))
{
$total_score = 0;
$avg = count($result[$subject_name]);
$test_results = "";
$i = 1;
foreach($result[$subject_name] AS $SN)
{
if($i == 1)
{
$ie = "1<sup>st</sup>";
}
elseif($i == 2)
{
$ie = "<br>2<sup>nd</sup>";
}
elseif($i == 3)
{
$ie = "<br>3<sup>rd</sup>";
}
else
{
$ie = "<br>4<sup>th</sup>";
}
$test_results .= "$ie Test: $SN ";
$total_score += $SN;
$avg_score = $total_score/$avg;
$i++;
}
}
else
{
$total_score = $test_results = "N/A";
}
?>
<tr>
<td style="border: 1px solid black; font-size:11px;width:120px;white-space: nowrap;height:30px;"><?=$subject_name?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$test_results?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$avg_score?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$remark?></td>
</tr>
<?php
}
?>
</tbody>
Could you make the html where you create the row conditional on $test_results NOT being equal to "N/A"? Something like this:
<?php if(!$test_results === "N/A"){ ?>
<tr>
<td> etc etc
<td> etc etc
<td> etc etc
<td> etc etc
</tr>
<?php } ?>

Results are not displaying in view

Recently, I discovered that the exam scores of students are not displaying anymore in a particular class (PRE-NURSERY).
Going back to the form where results are added, I see that the results have been repopulated and are already stored in the database.
However, they are not been displayed in the view. I wonder what must be wrong.
model
public function getRecentmtGradesRN($id)
{
$this->db->select('*');
$this->db->where('student_id', $id);
return $this->db->get('mtscores_rn')->result();
}
controller
public function view($id)
{
if (!$this->rbac->hasPrivilege('student', 'can_view')) {
access_denied();
}
$data['title'] = 'Student Details';
$student = $this->student_model->get($id);
$gradeList = $this->grade_model->get();
if($class_id == 2 || $class_id == 3) //see here
{
$subjectmtScores = $this->student_model->getRecentmtGradesRN($id);
}
else
{
$subjectmtScores = $this->student_model->getRecentmtGrades($id);
}
$studentSession = $this->student_model->getStudentSession($id);
$timeline = $this->timeline_model->getStudentTimeline($id, $status = '');
$data["timeline_list"] = $timeline;
$student_session_id = $studentSession["student_session_id"];
$student_session = $studentSession["session"];
$data['sch_setting'] = $this->sch_setting_detail;
$data['adm_auto_insert'] = $this->sch_setting_detail->adm_auto_insert;
$current_student_session = $this->student_model->get_studentsession($student['student_session_id']);
$data["session"] = $current_student_session["session"];
$student_due_fee = $this->studentfeemaster_model->getStudentFees($student['student_session_id']);
$student_discount_fee = $this->feediscount_model->getStudentFeesDiscount($student['student_session_id']);
$data['student_discount_fee'] = $student_discount_fee;
$data['student_due_fee'] = $student_due_fee;
$siblings = $this->student_model->getMySiblings($student['parent_id'], $student['id']);
$student_doc = $this->student_model->getstudentdoc($id);
$data['student_doc'] = $student_doc;
$data['student_doc_id'] = $id;
$category_list = $this->category_model->get();
$data['category_list'] = $category_list;
$data['gradeList'] = $gradeList;
$data['subjectmtScores'] = $subjectmtScores; //see here
//var_dump($subjectmtScores); die();
$data['student'] = $student;
$data['siblings'] = $siblings;
$class_section = $this->student_model->getClassSection($student["class_id"]);
$data["class_section"] = $class_section;
$session = $this->setting_model->getCurrentSession();
$studentlistbysection = $this->student_model->getStudentClassSection($student["class_id"], $session);
$data["studentlistbysection"] = $studentlistbysection;
$data['guardian_credential'] = $this->student_model->guardian_credential($student['parent_id']);
$data['reason'] = $this->disable_reason_model->get();
if ($student['is_active'] = 'no') {
$data['reason_data'] = $this->disable_reason_model->get($student['dis_reason']);
}
// //var_dump($data['teacher_comment']);
$this->load->view('layout/header', $data);
$this->load->view('student/studentShow', $data);
$this->load->view('layout/footer', $data);
}
view
<table class="table table-bordered" style="border: 1px solid black;">
<caption class="text-center">ACADEMIC PERFORMANCE</caption>
<thead>
<tr style="border: 1px solid black;">
<th style="border: 1px solid black; font-size:11px;width:120px;text-align:center;">
SUBJECTS
</th>
<th style="border: 1px solid black; font-size:11px;text-align:center;">CLASS
EXPECTATION
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">MILESTONE
ACHIEVED
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">REMARKS</th>
</tr>
</thead>
<tbody>
<?php $i = 1;
$total = 0;
$count = count($subjectmtScores);
foreach ($subjectmtScores as $value) { ?>
<?php
$mt_tot_score = $value->mt_ca1 + $value->mt_ca2 + $value->mt_ca3 + $value->mt_ca4 + $value->mt_affective + $value->mt_psychomotor + $value->mt_exam;
if ($mt_tot_score >= 80) {
$grade = 'A';
$remark = 'EXCELLENT';
} elseif ($mt_tot_score >= 70 && $mt_tot_score <= 79.99) {
$grade = 'B';
$remark = 'VERY GOOD';
} elseif ($mt_tot_score >= 60 && $mt_tot_score <= 69.99) {
$grade = 'C';
$remark = 'GOOD';
} elseif ($mt_tot_score >= 50 && $mt_tot_score <= 59.99) {
$grade = 'E';
$remark = 'PASS';
} elseif ($mt_tot_score >= 40 && $mt_tot_score <= 49.99) {
$grade = 'F';
$remark = 'FAIR';
} elseif ($mt_tot_score >= 0 && $mt_tot_score<= 39.99) {
$grade = 'FL';
$remark = 'FINAL LETTER GRADE';
}
?>
<?php
$total += $mt_tot_score;
?>
<tr style="border: 1px solid black;">
<td style="border: 1px solid black;font-size:12px;text-align:left;height:30px;"><?php echo $CI->GetSubjectNameWithID($value->subject_id); ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca1; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca2; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:left;white-space:nowrap;"><?php echo $value->mt_ca3; ?></td>
</tr>
<?php $i++;
} ?>
</tbody style="
white-space: nowrap;
">
</table>

Keep values in input fields - php array

I have a php array that includes inputs for posting. It uses a counter for each array record, and this counter is applied to the name of the input to be used in performing some actions with the post - this is working great.
The issue is that I would like to keep the users' existing inputs and re-populate the input fields in the array if their post doesn't pass validation.
I have done this before with static fields, simply storing the post variable and echoing it in the "value" --- but I can't figure out how to do this when working with an array. Anyone have any ideas?
$counter = 0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr height='60'>";
echo "<td class='mainlist'><input type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt'></td>";
echo "</tr>";
$counter = $counter + 1;
}
echo "</table>";
Full code per request:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$userid = $_SESSION['login_user'];
$companyid = $_POST['companyid'];
$options = $_POST['options'];
$counter = $_POST['hiddencounter'];
$runningtotal=0;
$totaloptions = array_sum($options);
$result = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$checknewcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."' and company_id = '" .$companyid[$i]."'");
if($checknewcompanies->num_rows == 1)
{ // do nothing
}
else
{
$runningtotal = $runningtotal + 1;
}
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$checkcurrentcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."'");
$countcompanies = $checkcurrentcompanies->num_rows;
$countcheck = $runningtotal + $countcompanies;
if($countcheck <= 4)
{
while($row = mysqli_fetch_array($result))
{
$balance = $row['options_balance'];
}
if ($totaloptions>$balance)
{
$notenoughoptions= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You don't have enough options! Try investing less!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i])){ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else {
if(!ctype_digit($options[$i]) or !is_numeric($options[$i])){
$charactercheck= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! Please enter only positive numbers to invest!</div>";
}
else {
$checkcompanies = mysqli_query($connection, "SELECT company_id FROM company_main WHERE company_id = '".$companyid[$i]."'");
if($checkcompanies->num_rows != 1)
{
$companynotexist= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! That company doesn't exist!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested)
VALUES($userid,$companyid[$i],$options[$i])";
mysqli_query($connection, $query);
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$balancecheck = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
while($row = mysqli_fetch_array($balancecheck))
{
$balance2 = $row['options_balance'];
}
if($balance2 > 0)
{
header('Location: user_invest.php');
}
else
{
header('Location: user_market.php');
}
} // end company check
} //end character check
} //end empty option check
} //end loop
} /* END OF NOT ENOUGH OPTIONS CHECK */
}
else
{
$toomanycompanies = "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You can invest in a maximum of 4 companies per week. Please choose fewer companies, or invest more in some of your existing companies!</div>";
/* echo "Maximum number of companies you can invest in is 4";
echo "<br />";
echo "Companies you already are invested in: ".$countcompanies;
echo "<br />";
echo "New companies you are trying to invest in: ".$runningtotal;
echo "<br />";
echo "Total: ".$countcheck;*/
}
} /* END OF ISSET CHECK */
else
{
}
?>
<?php
$result = mysqli_query($connection,"SELECT * from company_main");
$counter=0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr height='60'>";
echo "<td class='mainlist' width=140 align='center'>" . "<img src='".$row['company_logo']."' width='40'/>" . "</td>";
echo "<td class='mainlist' align='left' width=390 style='font-size: 15px;'>" . $row['company_name'] . "</td>";
echo "<input type=hidden name=companyid[$counter] value=" . $row['company_id'] . " />";
echo "<td class='mainlist'><input value='{$_POST['options[$counter]']}' type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt' style=' background-color: #FCFCFC;
border: solid 1px #CCCCCC;
font-size: 12px;
padding: 5px;
height: 20px;
text-align: right;'></td>";
echo "</tr>";
$counter=$counter+1;
}
echo "</table>";
echo "<input type='hidden' name='hiddencounter' value='$counter'>";
echo "
<table>
<tr>
<td width='630' height='50'></td>
<td align='right' width='60' style='color: #848580; font-size: 20px;'>Total: </td>
<td align='right' width='40' style='color: #94D90B; font-size: 20px; font-weight: bold; padding-right:20px;'><span id='sum'>0</span></td><td width='10'></td>
</tr><tr height='20px'></tr><tr>
<td width='570' align='center' style='color: #94D90B; font-size: 12px;'>";?>
<?php echo $notenoughoptions; ?>
<?php echo $charactercheck; ?>
<?php echo $toomanycompanies; ?>
<?php echo "
</td>
<td colspan='2' width='100' align='right'><input name='userinvestoptionsdynamic' type='submit' value='Invest!'></td><td width='10'></td>
</tr>
<tr height='20px'></tr>
</table>";
echo "</form>";
?>
The correct syntax is:
echo "{$arrayname($keyname)}";
So for example echo('value=' . $_POST['options'][$counter]); becomes:
echo "value={$_POST['options'][$counter]}";

using PHP to get information in xml file. How to make it shorter and expandable in the future?

These are the working codes that i have done. the program is about accessing information in an xml file such as student's name,id and marks based on group and team number submitted from a form. there are 2 submit buttons if one button is clicked, it will display with an additional element (pic) and the other one without it. so far so good.
but looking at the php codes, i know that i will be facing problems if there are numerous groups and team numbers. there would be a lot of if-else statements and the codes would be very long. i have tried using foreach but i'm not getting the result that i want. are there anyways to simplify this? i have been searching on the web but it seems that i just don't know how to implement them. quite new to this.
<html><style>
.datagrid table { border-collapse: collapse; text-align: center; width: 100%; }
.datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif;
background: #fff;
overflow: hidden;
border: 4px solid #006699;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px; }
.datagrid table td, .datagrid table th { padding: 7px 20px; }
.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );
background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');
background-color:#006699; color:#FFFFFF; font-size:15px; font-weight:bold;
border-left: 1px solid #0070A8; }
.datagrid table thead th:first-child { border: none; }
.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 13px;font-weight: normal; }
.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }
.datagrid table tbody td:first-child { border-left: none; }
.datagrid table tbody tr:last-child td { border-bottom: none; }
</style>
<center>
<form action="" method="post" >
<select name="group">
<option value="csa">CSA</option>
<option value="csb">CSB</option>
</select>
Enter team number:<input type="text" name="teamnum" value="">
<input type="submit" name="submit1" value="With Photo">
<input type="submit" name="submit2" value="Without Photo">
</form>
<form action="index.php">
<input type="submit" value="main">
</form>
</center>
</html>
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if (isset($_POST['submit2']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2)= each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
?>
i have found the way to solve this by using foreach
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
echo "<tbody>";
foreach ($xml->xpath("//student[contains(teamNum, $teamnum) and contains(group, $group)]") as $student) {
echo "<tr class='alt'>";
echo "<td>".$student->picture."</td>";
echo "<td>".$student->name."</td>";
echo "<td>".$student->id."</td>";
echo "<td>".$student->total."</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}else echo 'no data';
} else {
echo "enter a team's number";
}
?>
the trick is in the xpath. it selects all students that contains submitted values. after that it will be as $student and i will be able to output the element values from there.

alternating row colors

I am looking for a solution to use the alternating colors row design in my table which is from a csv.
my code:
<?php
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n
<thead>
<tr>
<th>data</th>
</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr class='odds'>";
foreach ($line as $cell) {
echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table>";
?>
so how can i have the tr class to alternate from odds and even?
thanks
have a variable
int count =0;
increment count on every iteration and take modolous by
count % 2
if(count % 2 == 0)
color = red //(make color of row = red)
else
color = yellow //(make color of row = yello)
count=count+1;
thats just an idea, u can accomodate this in ur code
You could use the css pseudo-selector :nth-of-type(odd|even)
http://reference.sitepoint.com/css/pseudoclass-nthoftype
If the ID of the table is styledTable, your stylesheet would look like:
#styledTable {
text-align: left;
width: 99%;
border: 1px solid black;
}
#styledTable tr:nth-of-type(even) {
background-color: red;
}
#styledTable tr:nth-of-type(odd) {
background-color: blue;
}
<?php
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n
<thead>
<tr>
<th>data</th>
</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
$i = 0;
while (($line = fgetcsv($f)) !== false) {
echo "<tr style='background-color: ".(($i%2)?'green':'blue').";'>";
foreach ($line as $cell) {
echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
$i++;
}
fclose($f);
echo "\n</table>";
?>
Or you could assign a class just the same way and style it using css. This is much better practice.
I will give you a better but much simpler solution, through CSS. First of all uniquely identify your table, i will show you a more general option.
table tr { backgroun: #ddd; }
table tr:nth-child(2n) { background: #ccc; }

Categories