I have a small PHP function that is called from one of my pages.
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
//SHOW STARS
if($rating == 0) { $stars = "notYet.jpg"; }
if($rating == 1) { $stars = "starOne.jpg"; }
if($rating == 1.5) { $stars = "starOneHalf.jpg"; }
if($rating == 2) { $stars = "starTwo.jpg"; }
if($rating == 2.5) { $stars = "starTwoHalf.jpg"; }
if($rating == 3) { $stars = "starThree.jpg"; }
if($rating == 3.5) { $stars = "starThreeHalf.jpg"; }
if($rating == 4) { $stars = "starFour.jpg"; }
if($rating == 4.5) { $stars = "starFourHalf.jpg"; }
if($rating == 5) { $stars = "starFive.jpg"; }
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
}
But when it runs in IE (7 or 8), it throws this error:
A script on this page is causing Internet Explorer to run slowly. Bla bla bla...
I call this function from two pages and both cause the same error. If I remove the call from the page, the page loads fine.
There is no javascript involved with the pages in question...
Help, help, help... I don't have much hair left...
Rick
What's happening is that it's taking a long time to execute your script. IE is waiting for output from the server but it's taking a long time.
You may want to try either a call to flush() every row (or maybe every 25 rows using the modulus operator) or using ob_implicit_flush() to turn on implicit flushing. That way you have data continually coming back to the browser (I assume you have a huge amount of data). You probably will also need to call set_timeout(0) to disable the 30 second time limit on your script.
The first thing I would do is get rid of all those IF statements for the stars, either using an array for them or a switch statement, either of which would reduce the processing required for your script. An array would be my approach. Your code would look something like the following:
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
// Declare the array for the stars.
$astars = array(
0=> "notYet.jpg",
1=> "starOne.jpg",
1.5=> "starOneHalf.jpg",
2=> "starTwo.jpg",
2.5=> "starTwoHalf.jpg",
3=> "starThree.jpg",
3.5=> "starThreeHalf.jpg",
4=> "starFour.jpg",
4.5=> "starFourHalf.jpg",
5=> "starFive.jpg"
);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
$stars = $astars[$rating];
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
The decimals may cause a problem in the array; if so, you can enclose the keys in quotes; e.g., "1.5"=>"starOneHalf.jpg"
The other thing you could do is create a variable for the HTML output instead of echoing the output every line, and then just echo the output at the end.
I found my problem...
The table within my function was assigned a css class. This particular css class contained a behavior, which called PIE.htc. Apparently, this caused some sort of IE melt down whenever it was called. I removed PIE (bummer, no more rounded corners or shadows in IE) and my problem is solved!!!
Thanks to everyone who provided assistance along the way!!!
Related
I've been around for years on Stack but this is my first time posting. I'm working on a website (php + mysql) and the following problem is driving me absolutely nuts.
I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:
SELECT Size, Amount FROM database WHERE product = 'product123' ORDER BY Size ASC
The php echo outputs an html table displaying Size and the corresponding available packs (Amount).
Echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>'
Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:
Size | Amount
1 | 10
1 | 50
2 | 10
2+ | 10
3 | 40
3+ | 25
3+ | 40
4+ | 25
What I'm looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:
Size | Amount
1 | 10 < yellow
1 | 50 < yellow
2 | 10 < transparent
2+ | 10 < yellow
3 | 40 < transparent
3+ | 25 < yellow
3+ | 40 < yellow
4+ | 25 < transparent
So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.
I can't figure out how to achieve this with php. The difficulty is that I can't use an evaluation based on odd/even since there sometimes is a "+" involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that "+" is not an option unfortunately.
I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can't figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.
Just a MCVE:
// your data
$records[] = array('size' => "1");
$records[] = array('size' => "1");
$records[] = array('size' => "2");
$records[] = array('size' => "2+");
$records[] = array('size' => "3");
$records[] = array('size' => "3+");
$records[] = array('size' => "3+");
$records[] = array('size' => "4");
$lastSize = $records[0]['size'];
$color = "yellow";
foreach ($records as $record) {
if ($lastSize != $record['size']) {
$lastSize = $record['size'];
if ($color == "yellow") $color = "transparent";
else $color = "yellow";
}
$lastSize == $record['size'];
echo $record['size'].' - '.$color.'<br>';
}
// OUTPUT:
// 1 - yellow
// 1 - yellow
// 2 - transparent
// 2+ - yellow
// 3 - transparent
// 3+ - yellow
// 3+ - yellow
// 4 - transparent
Ok, we'll start at the end. You probably want to put your color on the <tr>. The cleanest way to do it would be using css classes.
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
We'll figure out how to get the right value into $newSize in a moment. Next, we need the css for classes above, so make sure this is in your styles somewhere:
.transparentRow {
background-color: transparent;
}
.yellowRow {
background-color: yellow;
}
Ok, lets rip the + off the size:
$plainSize = trim($record['size'], '+')
Ok, we use that for comparison, using an ever changing $oldSize valiable. Here is a full, functional, block:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
$newSize = false;
} else {
$newSize = true;
}
$oldSize = $plainSize;
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
Some cleanup can lead to this:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
$oldSize = $plainSize;
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
I hope that helped not just with this problem, but with an example of how you can approach many other problems. Start at the end, work your way back.
As my comment suggested, use a double foreach() + implode() (and yet another solution):
<?php
$array[] = array("size"=>1,"amount"=>50);
$array[] = array("size"=>2,"amount"=>10);
$array[] = array("size"=>"2+","amount"=>10);
$array[] = array("size"=>3,"amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>"3+","amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>'4+',"amount"=>30);
// Sort by size
foreach($array as $row) {
$new[$row['size']][] = $row['amount'];
}
?>
<table>
<?php
$i = 0;
// Loop through the sorted groups
foreach($new as $size => $amts) {
// Determine odd or even
$color = ($i % 2 == 0)? "yellow":"transparent";
?> <tr>
<td class="<?php echo $color; ?>"><?php echo $size; ?></td>
<td class="<?php echo $color; ?>"><?php echo implode("</td>".PHP_EOL."</tr>".PHP_EOL."<tr>".PHP_EOL.'<td class="'.$color.'">'.$size.'</td><td class="'.$color.'">',$amts); ?></td>
</tr>
<?php $i++;
}
?>
</table>
You can do this using php sessions like this
session_start();
$_SESSION["pre_val"]='not set';
$_SESSION["pre_class"]='transparent';
//in your loop for showing table
//your loop starts
if($_SESSION["pre_val"]==$record['size']){
$suitable_class=$_SESSION["pre_class"];
}
else{
if($_SESSION["pre_class"]=='yellow'){$suitable_class='transparent';}
else{$suitable_class='yellow';}
}
//setting current values to session
$_SESSION["pre_class"] = $suitable_class;
$_SESSION["pre_val"] = $record['size'];
Echo '<tr class="$suitable_class"><td>'.$record['size'].'</td><td>'.$record['amount'].'</td></tr>';
//your loop ends
in your css
.yellow{background-color:yellow;}
.transparent{ background-color: rgba(255, 0, 0, 0.5);}
hope this solve your problem
Some for loop fun while printing out the table
$rows = array(
array("size"=>"1" ,"amount"=>"10"),
array("size"=>"1" ,"amount"=>"50"),
array("size"=>"2" ,"amount"=>"10"),
array("size"=>"2+","amount"=>"10"),
array("size"=>"3" ,"amount"=>"40"),
array("size"=>"3+","amount"=>"25"),
array("size"=>"3+","amount"=>"40"),
array("size"=>"4+","amount"=>"25")
);
echo "
<table>
<thead>
<tr><th>Size</th><th>Amount</th></tr>
</thead>
<tbody>";
$bgColors = ['transparent','yellow'];
$bgColor = 0;
echo "
<tr>
<td class='" . $bgColors[$bgColor] . "'>" . $rows[0]["size"] . "</td><td>" . $rows[0]["amount"] . "</td>
</tr>";
for($i = 1, $max = count($rows), $lastSize = $rows[0]; $i < $max; $lastSize = $rows[$i], $i++) {
if($rows[$i]["size"] !== $lastSize["size"])
$bgColor = ($bgColor + 1) % 2;
echo "
<tr>
<td style='background-color:" . $bgColors[$bgColor] . "'>" . $rows[$i]["size"] . "</td><td>" . $rows[$i]["amount"] . "</td>
</tr>";
}
echo "
</tbody>
</table>";
And an unasked for JS solution (assuming you've printed out the table as usual)
var rows = document.querySelectorAll('#sizeTable tbody td[name=size]');
var bgColors = ['transparent','yellow'];
var bgColor = 0;
for(var i = 1, lastSize = rows[0], max = rows.length; i < max; lastSize = rows[i],i++) {
if(rows[i].innerHTML !== lastSize.innerHTML) {
bgColor = (bgColor + 1) % 2;
}
rows[i].style['background-color'] = bgColors[bgColor];
}
you can keep the current size on a variable and if it changes you can change the color.
<html>
<head><title> Sample - Menukz </title></head>
<body>
<?php
/* Sample data array with size and amount */
$product['product123'] = array
(
array("size"=>"1", "amount"=>10),
array("size"=>"1", "amount"=>50),
array("size"=>"2", "amount"=>10),
array("size"=>"2+", "amount"=>10),
array("size"=>"3", "amount"=>40),
array("size"=>"3+", "amount"=>25),
array("size"=>"3+", "amount"=>40),
array("size"=>"4+", "amount"=>25)
);
$pre_size=0;
$pre_init=1;
echo "<table>";
foreach($product['product123'] as $row)
{
echo "<tr>";
/* Initialize */
if(strcmp($pre_size, $row['size']) !== 0 && $pre_init ===1)
{
$pre_size = $row['size'];
$pre_init = 0;
}
/* Change track */
if (strcmp($pre_size, $row['size']) !== 0 && $pre_init ===0)
{
echo "<td>Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
$pre_size = $row['size'];
}
else
{
echo "<td>Not Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
}
echo "</tr>";
}
?>
</body>
</html>
Thanks all for the proposed solutions. Berriel's MCVE works like a charm! However Stack doesn't let me +1 the answer yet.
I have one additional question:
I also have a second table in which the output of the first column can be any article code consisting of 10 chars limited to [a-z][0-9]. Since there is no predefined scheme such as in the Size table, I can't hardcode/predict any output like in most of the proposed solutions. However I still want to color the rows it in the same way described in my opening post.
I am not familiar with Stored Procedures or PDO in mysql. Is there any way to work around arrays with predefined content and still achieve the color grouping of rows with the same article code?
You can accomplish this using a nested repeat region.
First select your product by group WHERE product = 'product123' GROUP BY size
<?php
require ('conn.php');
try {
$prod = 'product123';
$sql = "SELECT * FROM sizes WHERE product=:prod GROUP BY size";
$query = $conn->prepare($sql);
$query->bindValue(':prod', $prod, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die('failed!');
}
?>
Then get all the products in each group ordered by amount inside a nested repeat region.
Each "grouped row" will alternate colors.
<table width="200" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Size</td>
<td>Amount</td>
</tr>
<?php
$i = 0;
do {
$i = $i + 1;
if ($i % 2 == 0){
echo '<tr bgcolor=#E4E4E4><td colspan="2">';
} else {
echo '<tr bgcolor=#EEEEEE><td colspan="2">';
}
try {
$group = $row['size'];
$sql = "SELECT * FROM sizes WHERE size=:group ORDER BY amount ASC";
$nested = $conn->prepare($sql);
$nested->bindValue(':group', $group, PDO::PARAM_INT);
$nested->execute();
$row_nested = $nested->fetch(PDO::FETCH_ASSOC);
$totalRows_nested = $nested->rowCount();
} catch (PDOException $e) {
die('nested failed');
}
echo '<table border="0" cellpadding="0" cellspacing="0" width="200">';
do {
echo '<tr><td width="100">'.$row_nested['size'].'</td><td width="100">'.$row_nested['amount'].'</td></tr>';
} while ($row_nested = $nested->fetch(PDO::FETCH_ASSOC));
echo '</table>';
echo '</td></tr>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
</table>
I help develop my school's website what I can not figure out is why on a certain page the sidebar and footer go into the table main. It only does this for two thing custodial and kitchen even when I think the code for say administrators is the same code and looks the same to me.
This is the code used to generate the teachers page
The link below will take you to the broken page since I can't post pictures
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=103
While the link below will take you to one that actually works
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=24
If you want the entire file for this code let me know and I will post a link
function dTeacher() {
global $db, $id;
if ($stmt = $db->prepare("SELECT name, department, schedule, education, whyteach, phone, email, image, quote FROM teachers WHERE id = ?"))
{
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();
$schedule = array();
$schedule = explode(",",$row['schedule']);
$education = explode(",",$row['education']);
$noshow = array(20, 14, 25, 15, 24, 21, 23);
print '<h1>Viewing '.$row['name'].'\'s Profile!</h1>';
if ($row['image']) {
print '<img style="max-width:40%; display: block; margin: 2% auto;" src="'.$row['image'].'" alt="Teacher Image Here">';
}
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
}
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
if ($row['phone'] || $row['email']) {
print '
<h3>Contact</h3>
<table id="maindata"><tr id="even"><td style="width:30%;">Phone</td><td>'.$row['phone'].'</td></tr>
<tr id="odd"><td style="width:30%;">Email</td><td>'.$row['email'].'</td></tr></table>';
}
if ($row['whyteach'] != "") {
print '<h3>Why do you teach?</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['whyteach'].'</p></td></tr></table>';
}
if ($row['quote'] != "") {
print '<h3>Favorite Quote</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['quote'].'</p></td></tr></table>';
}
}
else {
print "Error with your request.";
die();
}
}
You have a bug here, you are not closing table tag:
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
echo "</table>";
}
Because of this, when the profile has Schedule the table is not closed and the page will display bad.
And closes it here:
if ($row['education']) {
print "<h3>Education</h3>";
With two modifications the web should do its work fine.
Take a look this HTML validator, it will help you:
http://validator.w3.org/check?uri=http%3A%2F%2Fgwhs.kana.k12.wv.us%2Facademics%2Fdisplay.php%3Faction%3Dteacher%26id%3D103&charset=%28detect+automatically%29&doctype=Inline&group=0
Best regards.
First words: You should re-think the layout. Creating multiple tables to display page content is not the best approach and furthermore IDs have to be unique. So for valid HTML you can't have multiple tables with the ID maindata.
As mentioned by cmorrissey in the comments, you're not closing the first table, unless you enter the next if statement. Furthermore this part
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
of your code closes the previous <table id="maindata"> but opens a new one in each iteration of the loop. After the loop, your closing just one of them. So if it is correct, that you want to create multiple of these tables, you should close them in the loop as well:
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
print '</table>';
}
I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>
So, I asked this question earlier this week, and #newfurniturey helped me out, but now I have a new problem: I'd like to be able to put devices in that span more than one U (hence, the usize column in the devices db table) - some devices can span take up half a cabinet. Also, I'd like to be able to mark devices as being in the front or rear of the cabinet, but that should be simple enough for me to figure out.
Here's the working code (see old question for db setup) for just 1U devices:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function clickHandler(e)
{
var targetId, srcElement, targetElement;
if (window.event) e = window.event;
srcElement = e.srcElement? e.srcElement: e.target;
if (srcElement.className == "Outline")
{
targetId = srcElement.id + "d";
targetElement = document.getElementById(targetId);
if (targetElement.style.display == "none")
{
targetElement.style.display = "";
srcElement.src = "images/minus.gif";
}
else
{
targetElement.style.display = "none";
srcElement.src = "images/plus.gif";
}
}
}
document.onclick = clickHandler;
-->
</SCRIPT>
<noscript>You need Javascript enabled for this page to work correctly</noscript>
<?
function sql_conn()
{
$username="root";
$password="root";
$database="racks";
$server="localhost";
#mysql_connect($server,$username,$password) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to connect to $server [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
#mysql_select_db($database) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to select $database as a database [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
}
sql_conn();
$sql_datacenters="SELECT * FROM `datacenters`";
$result_datacenters=mysql_query($sql_datacenters);
$j=0;
echo "<table border='1' style='float:left;'>";
while ($datacenters_sqlrow=mysql_fetch_array($result_datacenters))
{
echo "<tr><td>";
echo "<h2 class='black' align='left'>";
echo "<IMG SRC='images/plus.gif' ID='Out" . $j . "' CLASS='Outline' STYLE='cursor:hand;cursor:pointer'>"; // fancy icon for expanding-collapsing section
echo " " . $datacenters_sqlrow['rack'] . ": " . $datacenters_sqlrow['cagenum'] . "</h2>"; // datacenter name and cage number
echo "<div id=\"Out" . $j . "d\" style=\"display:none\">"; // opening of div box for section that is to be expanded-collapsed
echo $datacenters_sqlrow['notes'] . "<br /><br />"; // datacenter notes
$sql_cabinets="SELECT * FROM `cabinets` WHERE `datacenter` = '$datacenters_sqlrow[0]' ORDER BY `cabinetnumber` ASC";
$result_cabinets=mysql_query($sql_cabinets);
while ($cabinets_sqlrow=mysql_fetch_array($result_cabinets))
{
$sql_devices="SELECT * FROM `devices` WHERE `datacenter` = '$datacenters_sqlrow[0]' AND `cabinet` = '$cabinets_sqlrow[1]' ORDER BY `ustartlocation` ASC";
$result_devices=mysql_query($sql_devices);
echo "<table border='1' style='float:left;'>"; // opening of table for all cabinets in datacenter
echo "<tr><td colspan='2' align='middle'>" . $cabinets_sqlrow[1] . "</td></tr>"; // cabinet number, spans U column and device name column
$devices = array();
while($row = mysql_fetch_array($result_devices)) {
$devices[$row['ustartlocation']] = $row['devicename'];
}
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) // iterates through number of U in cabinet
{
$u = $cabinets_sqlrow[2] - $i; // subtracts current $i value from number of U in cabinet since cabinets start their numbers from the bottom up
echo "<tr>";
echo "<td width='15px' align='right'>$u</td>"; // U number
echo (isset($devices[$u]) ? "<td width='150px' align='middle'>$devices[$u]</td>" : "<td width='150px' align='middle'>empty</td>");
echo "</tr>";
}
echo "</table>"; // closes table opened earlier
}
echo "</td></tr>";
echo "</div>"; // close for div box that needs expanding-collapsing by fancy java
$j++; // iteration for the fancy java expand-collapse
}
echo "</table>";
mysql_close();
?>
Based on your previous question, each ustartlocation is unique (hence why you can use it as an index in your $devices array). Using this same concept, you could populate the $devices array from "ustartlocation to (ustartlocation + (usize - 1))".
$devices = array();
while($row = mysql_fetch_array($result_devices)) {
$endLocation = ($row['ustartlocation'] + ($row['usize'] - 1));
for ($location = $row['ustartlocation']; $location <= $endLocation; $location++) {
$devices[$location] = $row['devicename'];
}
}
Because your display-loop already iterates through each U and displays the device assigned, you shouldn't need to modify any other portion. However, the caveat to this is that the device-name will repeat for every U instead of span it. To span it, we'll need to do a little more work.
To start, we could just store the usize in the $devices array instead of filling in each individual position. Also, to prevent a lot of extra work/calculations later, we'll also store a "placeholder" device for each additional position.
while($row = mysql_fetch_array($result_devices)) {
// get the "top" location for the current device
$topLocation = ($row['ustartlocation'] + $row['usize'] - 1);
// populate the real position
$devices[$topLocation] = $row;
// generate a list of "placeholder" positions
for ($location = ($topLocation - 1); $location >= $row['ustartlocation']; $location--) {
$devices[$location] = 'placeholder';
}
}
Next, in your display-loop, you will check if the current position is a placeholder or not (if so, just display the U and do nothing for the device; if it isn't, display the device, or 'empty'). To achieve the "span" effect for each device, we'll set the cell's rowspan equal to the device's usize. If it's 1, it will be a single cell; 2, it will span 2 rows, etc (this is why "doing nothing" for the device on the placeholder-rows will work):
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) {
$u = $cabinets_sqlrow[2] - $i;
echo "<tr>";
echo '<td width="15px" align="right">' . $u . '</td>';
if (isset($devices[$u])) {
// we have a "device" here; if it's a "placeholder", do nothing!
if ($devices[$u] != 'placeholder') {
echo '<td width="150px" align="middle" rowspan="' . $devices[$u]['usize'] . '">' . $devices[$u]['devicename'] . '</td>';
}
} else {
echo '<td width="150px" align="middle">empty</td>';
}
echo "</tr>";
}
So, as it can be seen - the first method above that simply repeats the device for each U it spans is much simpler. However, the second method will present a more user-friendly display. It's your preference to which method you want to use and which one you think will be more maintainable in the future.
UPDATE (code-fix & multi-direction spanning)
I didn't realize that your table was being built in descending-order so I had the ustartlocation as the "top location" which caused an erroneous row/cell shift. I've fixed the code above to properly set a "top location" based on the ustartlocation and usize for each device that will fix that issue.
Alternatively, as direction may or may not be important, I've customized the $devices-populating loop (below) to support creating a row-span that goes either upwards or downwards, completely depending on the flag you specify. The only code you'll need to change (if you already have the customized display-loop from above) would be the while loop that populates $devices:
$spanDevicesUpwards = true;
while($row = mysql_fetch_array($result_devices)) {
if ($row['usize'] == 1) {
$devices[$row['ustartlocation']] = $row;
} else {
$topLocation = ($spanDevicesUpwards ? ($row['ustartlocation'] + $row['usize'] - 1) : $row['ustartlocation']);
$bottomLocation = ($spanDevicesUpwards ? $row['ustartlocation'] : ($row['ustartlocation'] - $row['usize'] + 1));
$devices[$topLocation] = $row;
for ($location = ($topLocation - 1); $location >= $bottomLocation; $location--) {
$devices[$location] = 'placeholder';
}
}
}
This new block of code will, if the usize spans more than 1, determine the "top cell" and "bottom cell" for the current device. If you're spanning upwards, the top-cell is ustartlocation + usize - 1; if you're spanning downwards, it's simply ustartlocation. The bottom-location is also determined in this manner.
Hoping this will work for you..........for front/rear you can name you device as SERVER3/front or SERVER3/rear:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function clickHandler(e)
{
var targetId, srcElement, targetElement;
if (window.event) e = window.event;
srcElement = e.srcElement? e.srcElement: e.target;
if (srcElement.className == "Outline")
{
targetId = srcElement.id + "d";
targetElement = document.getElementById(targetId);
if (targetElement.style.display == "none")
{
targetElement.style.display = "";
srcElement.src = "images/minus.gif";
}
else
{
targetElement.style.display = "none";
srcElement.src = "images/plus.gif";
}
}
}
document.onclick = clickHandler;
-->
</SCRIPT>
<noscript>You need Javascript enabled for this page to work correctly</noscript>
<?
function sql_conn()
{
$username="root";
$password="root";
$database="racks";
$server="localhost";
#mysql_connect($server,$username,$password) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to connect to $server [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
#mysql_select_db($database) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to select $database as a database [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
}
sql_conn();
$sql_datacenters="SELECT * FROM `datacenters`";
$result_datacenters=mysql_query($sql_datacenters);
$j=0;
echo "<table border='1' style='float:left;'>";
while ($datacenters_sqlrow=mysql_fetch_array($result_datacenters))
{
echo "<tr><td>";
echo "<h2 class='black' align='left'>";
echo "<IMG SRC='images/plus.gif' ID='Out" . $j . "' CLASS='Outline' STYLE='cursor:hand;cursor:pointer'>"; // fancy icon for expanding-collapsing section
echo " " . $datacenters_sqlrow['rack'] . ": " . $datacenters_sqlrow['cagenum'] . "</h2>"; // datacenter name and cage number
echo "<div id=\"Out" . $j . "d\" style=\"display:none\">"; // opening of div box for section that is to be expanded-collapsed
echo $datacenters_sqlrow['notes'] . "<br /><br />"; // datacenter notes
$sql_cabinets="SELECT * FROM `cabinets` WHERE `datacenter` = '$datacenters_sqlrow[0]' ORDER BY `cabinetnumber` ASC";
$result_cabinets=mysql_query($sql_cabinets);
while ($cabinets_sqlrow=mysql_fetch_array($result_cabinets))
{
$sql_devices="SELECT * FROM `devices` WHERE `datacenter` = '$datacenters_sqlrow[0]' AND `cabinet` = '$cabinets_sqlrow[1]' ORDER BY `ustartlocation` ASC";
$result_devices=mysql_query($sql_devices);
echo "<table border='1' style='float:left;'>"; // opening of table for all cabinets in datacenter
echo "<tr><td colspan='2' align='middle'>" . $cabinets_sqlrow[1] . "</td></tr>"; // cabinet number, spans U column and device name column
$devices = array();
$devices_size=array();
while($row = mysql_fetch_array($result_devices)) {
$devices[$row['ustartlocation']] = $row['devicename'];
//$devices_size[$row['ustartlocation']+$row['usize']-1] = $row['usize'];
$devices_size[$row['ustartlocation']] = $row['usize'];
}
$start="";
$new="";
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) // iterates through number of U in cabinet
{
$u = $cabinets_sqlrow[2] - $i; // subtracts current $i value from number of U in cabinet since cabinets start their numbers from the bottom up
echo "<tr>";
echo "<td width='15px' align='right'>$u</td>"; // U number
$rowspan=$devices_size[$u];
//$rowspan1=$
if($rowspan>1)
{
$start=$u;
$new=$u-$rowspan+1;
echo (isset($devices[$u]) ? "<td width='150px' align='middle' rowspan='".$rowspan."'>$devices[$u]</td>" : "<td width='150px' align='middle' rowspan='".$rowspan."'>$devices[$new]</td>");
}
else{
if($u<=$start && $u>=$new)
{
}
else
{
echo (isset($devices[$u]) ? "<td width='150px' align='middle' >$devices[$u]</td>" : "<td width='150px' align='middle'>empty".$row."".$u."</td>");
}
}
echo "</tr>";
}
echo "</table>"; // closes table opened earlier
}
echo "</td></tr>";
echo "</div>"; // close for div box that needs expanding-collapsing by fancy java
$j++; // iteration for the fancy java expand-collapse
}
echo "</table>";
mysql_close();
?>
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana = $banana + 1;
if ($total_price2!=0)
{
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
Problems:
The "banana" alternates the colour of the table row (class="alt") by using modulus (%) to check if banana is a odd number.
Not Working, I see the browser is self-closing the opening <tr> tag.
eg:
<tr><td>person</td><td>data</td><td>$10.00</td></tr>
<tr class="alt"></tr> (Repeats in this fashion)
UPDATE
I have discovered that the reiterating banana always returns ODD NUMBERS: 1 , 3, 5, etc
MySQL is not running correctly
SELECT table1.member, table1.paid, table1.payment,table2.qty,table3.number FROM table1,table2,table3 WHERE table1.member = table2.member AND table1.payment="fruit"
It is giving me wrong data like so:
person1 $10.00
person1 $0.00
person2 $10.00
person2 $0.00
etc
If all else fails, you could just use CSS:
tr {background-color: blue;}
tr:nth-of-type(2n) {background-color: red;}
Try doing this for a debug first:
echo "<tr class=\"alt\"> ";
My guess is that you have no data contained in your <tr> and is being squished to 0 px tall by your browser.
EDIT: I'm not entirely sure giving a class to your <tr> will filter down into the <td> based on certain browser DOM parsing. Whenever I do a zebra row, I'll assign the class to the <td>. I'm no designer by any standard, though. :)
Humor me and try this please:
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana++;
if ($banana % 2 == 0) {
$td_class = "alt";
} else {
$td_class = "";
}
echo "<tr>";
if ($total_price2!=0) {
echo "<td class='{$td_class}'>".$rows3['member']."</td>";
echo "<td class='{$td_class}'>".$rows3['payment']."</td>";
echo "<td class='{$td_class}'>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
That's not going to work. You're only opening the table row if $total_price2!=0. It seems you should only output the closing </tr> tag inside that IF block.
Try this instead:
<?php
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
if ( !$total_price2)
continue;
$banana = $banana + 1;
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
echo "</tr>";
}