Nested Key-Value lookups in php - php

I am trying to make a "stock" website for a class at school, and it's my first dive into php. Basically, the script pulls down a CSV file form a google docs spreadsheet, and (attempts) to put the values into an array for use later. I'd like to show the top 5 rising and falling stocks, but am having issues. Here's main section of the script:
<html>
<head>
<?php
#Global Variables
$rising = array();
$falling = array();
$stocks = array();
#End Global Variables
#Function to read data from the spreadsheet
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
#Process data
function populateTicker(){
$document = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtrtT_MC9_YFdHRDUGx0a2xveXNfOHJVdXJ6bVNkMFE&output=csv";
$data= get_data($document);
$lines = explode("\n", $data);
$val = "";
foreach($lines as $key => $value){
if($key != 0){
$stockInfo = explode(",", $value);
$perChange = $stockInfo[3];
$perChangeVal = "up ";
if($perChange < 0){
$perChangeVal = "down ";
$falling['$stockInfo[0]'] = $perChange;
}else{
$rising['$stockInfo[0]'] = $perChange;
}
$stocks['$stockInfo[0]'] = array("symb" => $stockInfo[0], "name" => $stockInfo[1], "price" => $stockInfo[2]);
$val = $val . "(" . $stockInfo [0] . ") " . $stockInfo [1] . " " . "\$" . $stockInfo [2] . " " . $perChangeVal . $perChange . "% today" . "\v \v \v \v | \v \v \v \v";
}
}
//asort($falling);
//arsort($rising);
return $val;
}
function getRising($index){
if($index <= count($rising)){
$keys = array_keys($rising);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
function getFalling($index){
if($index <= count($falling)){
$keys = array_keys($falling);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
?>
</head>
<body>
<DIV id='DEBUG'>
<?php
print_r($stocks);
print_r($rising);
print_r($falling);
?>
</DIV>
<center><b><u><font size="+2">Latest Prices</font><br /></u></b></center>
<DIV ID="TICKER" STYLE="border-top:2px solid #CCCCCC; border-bottom:2px solid #CCCCCC; overflow:hidden; width:100%" onmouseover="TICKER_PAUSED=true" onmouseout="TICKER_PAUSED=false">
<?php echo populateTicker(); ?>
</DIV>
<script type="text/javascript" src="webticker_lib.js" language="javascript"></script>
<div id='Top5'>
<br />
<center><b>This page does not update automatically! Please refresh the page to update the information!</b></center>
<br />
<center><b><u><font size="+2">Top 5's</font><br /></u></b></center>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Top 5 Rising</th>
<th>Top 5 Falling</th>
</tr>
<tr>
<td><?php echo getRising(1); ?></td>
<td><?php echo getFalling(1); ?></td>
</tr>
<tr>
<td><?php echo getRising(2); ?></td>
<td><?php echo getFalling(2); ?></td>
</tr> <tr>
<td><?php echo getRising(3); ?></td>
<td><?php echo getFalling(3); ?></td>
</tr> <tr>
<td><?php echo getRising(4); ?></td>
<td><?php echo getFalling(4); ?></td>
</tr> <tr>
<td><?php echo getRising(5); ?></td>
<td><?php echo getFalling(5); ?></td>
</tr>
</table>
</center>
</div>
<br />
<center><b><u><font size="+2">All Stocks</font><br /></u></b></center>
<div id='All'>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Price</th>
<th>High</th>
<th>Low</th>
<th>Percent Change</th>
</tr>
<?php
#Dynamic Table Creation
foreach($stocks as $key => $value){
echo '<tr>';
echo '<td>(' . $value['symb'] . ')</td>';
echo '<td>' . $value['name'] . '</td>';
echo '<td>' . $value['price'] . '</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>' . $vaule['perChange'] . '</td>';
echo '</tr>';
}
?>
</table>
</center>
</div>
</body>
<footer>
</footer>
</html>
But nothing gets assigned to the arrays. Any help would be appreciated.
UPDATE: I added the full source of the front page, index.php
UPDATE2: I figured it out. I come from java, and didn't fully understand how the scope of variables worked in php. A simple
<?php
global $rising, $falling, $stocks;
...
?>
did the trick

I don't know exactly about your code but I can show an example for presenting the nested arrays:
$arr = array('1' => array('1', '2'), '2');
function showNested($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
echo $value;
showNested($array);
}
else
{
echo $value;
}
}
}
UPDATE
You used $stocks['$stockInfo[0]'] in your code. I think this kind of syntax would never do anything. Totally when you use a variable in a string, you should surround it by {}. And one thing else that I never tested it before, I don't think putting an array with an index in a string would help the PHP to understand what's the current data in [].

Related

Taking certain parts of a line and putting chosen elements into a table, it's only reading the first line several times

Let's say I have multiple lines in a text file where every line looks like this:
2, Ann, Johnsson, AJ#email.com, University of smth, street 1, state, country, 49008, +12202202220
I am reading the data from said textfile and trying to put it into a table. I have taken the data and put it into an array and then to separate the data I don't want, I echo all the elements that I wanna put into the table.
<table class="table">
<tr>
<th>Name</th>
<th>Email</th>
<th>University</th>
<th>City</th>
</tr>
<?php
$file = fopen("customers.txt", "r"); {
$line = fgets($file);
$customers = explode(",", $line);
list($studentid, $firstname, $lastname, $email, $university, $adress, $city, $country, $phonenumber) = $customers;
echo $firstname;
echo $lastname;
echo $email;
echo $university;
echo $city;
foreach($customers as $customer) {
echo '<tr>';
echo '<td>'.'<a>' . $firstname, " ", $lastname . '</a>'.'</td>';
echo '<td>' . $email . '</td>';
echo '<td>' . $university. '</td>';
echo '<td>' . $city . '</td>';
echo '</tr> ';
}
}
?>
</table>
</div>
Can someone explain what I am missing, my table only outputs the first line of the text file.
fgets causing this error.just change it to file_get_contents. It will return all of the content of the filem
When defining $customers it looks like you're splitting that single line into it's relevant "cells" or "fields".
Then you're looping over the cells instead of the lines.
If you're instead trying to loop over each line, try something like this:
<?php
$file = fopen("customers.txt", "r");
while ($line = fgets($file)) {
$customer = explode(",", $line);
list($studentid, $firstname, $lastname, $email, $university, $adress, $city, $country, $phonenumber) = $customer;
?>
<tr>
<td><a><?php echo $firstname . " " . $lastname; ?></a></td>
<td><?php echo $email; ?></td>
<td><?php echo $university; ?></td>
<td><?php echo $city; ?></td>
</tr>
<?php
}
?>

How to Not display empty rows?

My question is:
If you look at where it would display "
<td>1ST<?php echo $first ?></td>
"
How do I ensure that if the row associate to variable '$first' or all the others if they are empty nothing shows. Also that the '1st' doesn't show?
Have tried various things I am stumped on this!
<h2><?php echo $show_title ?></h2>
<h4>Show Date: <span class="glyphicon glyphicon-time"> </span><?php echo $show_date ?></h4>
<hr>
</a>
<hr>
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$dog_name = $row['dog_name'];
$placement = $row['placement'];
$class_name = $row['class_name'];
$entries = $row['entries'];
$absentee = $row['absentee'];
$entries = $row['entries'];
$first = $row['first'];
$second = $row['second'];
$third = $row['third'];
$RES = $row['RES'];
$VHC = $row['VHC'];
$DCC = $row['DCC'];
$RDCC = $row['RDCC'];
$BCC = $row['BCC'];
$RBCC = $row['RBCC'];
$BOB = $row['BOB'];
$BP = $row['BP'];
$BJ = $row['BJ'];
?>
<table class="table" border="0"></div>
<tr>
<td><strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6></td>
<td></td>
</tr>
<tr>
<td>DCC</td>
<td><?php echo $DCC ?></td>
</tr>
<tr>
<td>RDCC</td>
<td><?php echo $RDCC ?></td>
</tr>
<tr>
<td>BCC</td>
<td><?php echo $BCC ?></td>
</tr>
<tr>
<td>RBCC</td>
<td><?php echo $RBCC ?></td>
</tr>
<tr>
<td>BOB</td>
<td><?php echo $BOB ?></td>
</tr>
<tr>
<td>BP</td>
<td><?php echo $BP ?></td>
</tr>
<tr>
<td>BJ</td>
<td><?php echo $BJ ?></td>
</tr>
<tr>
<td>1ST</td>
<td><?php echo $first ?></td>
</tr>
<tr>
<td>2ND</td>
<td><?php echo $second ?></td>
</tr>
<tr>
<td>3RD</td>
<td><?php echo $third ?></td>
</tr>
<tr>
<td>RES</td>
<td><?php echo $RES ?></td>
</tr>
<tr>
<td>VHC</td>
<td><?php echo $VHC ?></td>
</tr>
</table>
You're doing well, just apply a filtering function to each row you recieve:
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query);
if (!$result) {
trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($connection), E_USER_ERROR);
} else {
// Fetch results into array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// If results array is not empty
if ($data) {
echo '<table class="table" border="0"></div>
<tr>
<td>
<strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6>
</td>
<td></td>
</tr>';
// Now let's walk through every record
array_walk($data, function($dogRecord) {
// Here we apply array_filter to each dog record, so that empty values (i.e. those evaluating to false) are filtered out
$dogRecord = array_filter($dogRecord);
// Now loop throw $dogRecord to build table
$collation = [
'DCC' => 'DCC',
'RDCC' => 'RDCC',
'BCC' => 'BCC',
'RBCC' => 'RBCC',
'BOB' => 'BOB',
'BP' => 'BOB',
'BJ' => 'BOB',
'1ST' => 'first',
'2ND' => 'second',
'3RD' => 'third',
'RES' => 'RES',
'VHC' => 'RES'
];
foreach ($dogRecord as $property => $value) {
echo '<tr>
<td>'.$collation[$property].'</td>
<td>'.$value.'</td>
</tr>';
}
});
echo '</table>';
}
}
Note that instead of simple foreach loop I'm using array_walk function. This is because since you extract variables for each record, you want undeclared (i.e. unoccupied) varables every time.
What about this:
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
// Show the table-row
}
}
The following code will iterate through each row in the result (while loop) and each key => value within each row (foreach loop); it will then check if a value is not null or the key is not equal to 'first' (if statement) and echo the results in the table element. I'm not sure I fully understood your question but I hope this helps in some small way.
<table>
<?php
if($result){
while($row = mysqli_fetch_assoc($result))
foreach($row as $key => $value){
if($value != null && $key != 'first'){
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
}
?>
</table>

how to get the content of current webpage in mpdf library

i have the below code written, actually i thought of converting the current webpage to pdf document, but i couldnt make how to declare the current url and get the contents of the webpage in pdf doc. below is my code.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
include "contractview.php?ID=129";
//This is your php page ?>
<?php
$html = ob_get_contents();
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
i have written include "contractview.php?ID=129"; but this was not working, can any one please help me in how to assign this to get the current page contents.
MPDF doesn't support includes. You have to put it in a var. The full html can be converted using jquery or in php with file_get_contents.
This is how i did it with full page.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
//$content = file_get_contents("contractview.php?ID=129"); //<=== WRONG ONE
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
print($content);
//This is your php page ?>
<?php
$html = ob_get_contents($content); //<=== put content in ob
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
I see you are using ob_start and ob_end
You coudl also use
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($content);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
<?php require_once ('header.php'); ?>
<!-- 10/15/2014 START: Freze table header row; Updated Fancybox so it works with jQuery 1.10.1 as well -->
<META content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" http-equiv="X-UA-Compatible">
<!--script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script duplicate 10/6/2015-->
<SCRIPT type="text/javascript" src="jQueryfloatThead/jquery.floatThead.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/site.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/bootstrap.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/less.js"></SCRIPT>
<!-- 10/15/2014 END -->
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border=0 cellpadding="0" cellspacing="0">
<tr><td height="36" background="images/topbar_bg.png" style="background-repeat:repeat-x;"><img src="images/topbar_bg.png" height="36"></td></tr>
<tr><td>
<table width="960" border=0 cellpadding="0" cellspacing="0" align="center">
<?php require_once ('topnav.php'); ?>
<tr><td>
<table width="100%" border=0 cellpadding="10" cellspacing="5">
<?php
if(!isset($_SESSION['Username'])) {
header('Location: home?errMsg=Your session has been expired. Please re-login again.');
}
?>
<tr><td bgcolor="#006ec7" valign="top" width="100%" class="headertd">FAR Compliance Portal</td></tr>
<tr><td bgcolor="#ebf4f9" valign="top" width="100%" height="300">
<?php
require_once ('dbconnection.php');
require_once ('contractcheck.php'); //Check if users can view this section
if (!isset($_REQUEST['ID'])) {
print "ERROR: No record has been selected.";
exit;
}
if (!is_numeric($_REQUEST['ID'])) {
print "ERROR: Invalid record has been selected.";
exit;
}
$thisID = $_REQUEST['ID'];
$sqlGet = "select * from far_contract where ID='" .$thisID. "'";
$resultGet = mysql_query($sqlGet, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [1] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows==0 || $num_rows>1) {
print "Error: Invalid record is being called ($thisID). Please check with administrator.";
exit;
}
$row = mysql_fetch_array($resultGet);
$thisID = $row[0];
$thisContractNumber = $row[1];
$thisCustomer = $row[2];
$thisCeilingValue = $row[3];
//$thisEffectiveDate = $row[4];
//$thisExpirationDate = $row[5];
//$thisLegalEntity = $row[6];
$thisProjectName = $row[4];
$thisMFilesLink = $row[5];
$thisCreatedByID = $row[6];
$thisCreatedDate = $row[7];
$thisModifiedByID = $row[8];
$thisModifiedDate = $row[9];
$thisContractStatus = $row[10]; //12/22/2014
$thisNotes = $row[11]; //3/27/2015
$thisSubmittedByID = $row[17]; //10/1/2015
$thisSubmittedDate = $row[18]; //10/1/2015
$thisMasterAgreement = $row[19]; //10/6/2015
if ($thisContractStatus==NULL) $thisContractStatus="Not Submitted"; //12/22/2014
$thisSpecialStatusNotes = $row[15]; //4/15/2015
unset($resultGet);
//if ($thisEffectiveDate!="") $thisEffectiveDate = date("m/d/Y", strtotime($thisEffectiveDate));
//if ($thisExpirationDate!="") $thisExpirationDate = date("m/d/Y", strtotime($thisExpirationDate));
$sqlGetFAR = "select * from far_contract_clauses where ContractID='" .$thisID. "'";
$resultGet = mysql_query($sqlGetFAR, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [2] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows>0) {
$thisSelectClause = "";
while ($row = mysql_fetch_array($resultGet)) {
if ($thisSelectClause=="")
$thisSelectClause = $row[2];
else
$thisSelectClause .= ",".$row[2];
}
}
unset($resultGet);
?>
<h1>Contract Records > View Record</h1>
<a href='php-to-pdf.php' target='_blank' ><input type='button' value='Convert to pdf'></a>
<table cellspacing=0 cellpadding=3 border=0 width="100%" class="table-bordered">
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>ID:</b></td>
<td class="resultTbl"><?php echo $thisID ?></td>
</tr>
<tr>
<td nowrap width="220" class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer's Solicitation/Contract Number:</b></td>
<td width="100%" class="resultTbl"><?php echo $thisContractNumber ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer:</b></td>
<td class="resultTbl"><?php echo $thisCustomer ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Ceiling Value ($):</b></td>
<td class="resultTbl"><?php is_numeric($thisCeilingValue)? print "$ ".number_format($thisCeilingValue,2) : print ""; ?></td>
</tr>
<!--<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Effective Date:</b></td>
<td class="resultTbl"><//php echo $thisEffectiveDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Expiration Date:</b></td>
<td class="resultTbl"><//php echo $thisExpirationDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Rapiscan Legal Entity:</b></td>
<td class="resultTbl"><//php echo $thisLegalEntity //></td>
</tr>-->
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Project Name/Description:</b></td><?php //3/27/2015 ?>
<td class="resultTbl"><?php echo $thisProjectName ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>M-Files Link:</b></td>
<td class="resultTbl"><?php echo $thisMFilesLink ?></td>
</tr>
<tr><?php //3/27/2015 ?>
<td class="resultTbl" bgcolor='#d9e0e4' valign='top'><b>Notes:</b></td>
<td class="resultTbl"><?php echo $thisNotes ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Created By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisCreatedByID) . " on " . $thisCreatedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisCreatedDate; //1/6/2015
if ($thisModifiedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Last Modified By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisModifiedByID) . " on " . $thisModifiedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisModifiedDate; //1/6/2015
}
?>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015 Added Submitted By and Submitted Date
if ($thisSubmittedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Submitted By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisSubmittedByID) . " on " . $thisSubmittedDate ?></td>
</tr>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015
}
?>
<?php
$MasterAgreement = $thisMasterAgreement; //10/1/2015 Added Submitted By and Submitted Date
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Master/Framework<b>Agreement Contract</b></td>
<td class="resultTbl"><?php echo ($thisMasterAgreement==1)?'Yes':'No'; ?></td>
</tr>
<?php
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Status:</b></td>
<td class="resultTbl"><?php echo $thisContractStatus //12/22/2014 ?>
<?php //4/15/2015
if ($AllowContractFull) {
if ($thisContractStatus=="Submitted") {
print " ";
print "[Suspend]";
print " [Cancel]";
} elseif ($thisContractStatus=="Suspended") {
print " ";
print "[Re-activate]";
print " [Cancel]";
}
}
if (! ($thisSpecialStatusNotes=="" || is_null($thisSpecialStatusNotes)) ) {
print "<BR><font color=gray>$thisSpecialStatusNotes</font>";
}
?>
</td>
</tr>
<tr><td valign=top colspan=2 class="resultTbl"><b>FAR Clauses:</b></td></tr>
<tr><td valign=top colspan=2 class="resultTbl">
<?php
//get list of departments
$sql = "select * from far_departments order by Department";
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [3]: ' . mysql_error();
exit;
}
$deptList = array();
while ($row = mysql_fetch_array($result)) { //loop each department
$deptList[] = $row[1];
}
unset ($result);
printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate); //1/6/2015
?>
</td>
</tr>
</table>
<?php
require_once ('logging.php'); //7/31/2014
mysql_close($dbconnection);
?>
</td></tr>
</table>
</td></tr>
<?php require_once ('footer.php'); ?>
</table>
</td></tr>
</table>
</body>
</html>
<?php
function printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate){ //1/6/2015
global $deptList;
global $dbconnection;
//print table header
//echo "<h1>Compliance Report</h1>";
echo "<DIV id='options'><table width='100%' class='table table-bordered table-striped' cellspacing=0 cellpadding=5>";
echo "<thead><tr bgcolor='#d9e0e4'>";
echo "<th class='resultTbl' nowrap><b>FAR Clauses</b><img src='images/spacer.gif' width='80' height='1'></th>"; //9/15/2014
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") //4/15/2015
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified<BR>as of<BR>".str_replace(" ", "<BR>", $SubmissionDate)."?</b></font></th>"; //1/6/2015
else
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified?</b></font></th>"; //9/15/2014
foreach ($deptList as $EachDept) { //loop each dept
echo "<th class='resultTbl' align=center><b>" . $EachDept . "</b></th>";
}
echo "</tr></thead>"; //10/15/2014 END
//get all questions
$sql = "select * from far_questions where QStatus='ACTIVE' and ID in ($thisSelectClause) order by Title, Alternate"; //2/9/2015
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [4]: ' . mysql_error();
exit;
}
$listQuestionArray = array(); //START natural-order sorting questions by title
while ($row = mysql_fetch_array($result)) {
$listQuestionArray[] = array($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7]); //2/9/2015; 10/10/2014; 6/17/2014
}
usort($listQuestionArray, function ($elem1, $elem2) {
return strnatcmp ($elem1['1']." ".$elem1['7'], $elem2['1']." ".$elem2['7']);
//2/9/2015 need to take Alternate in nartural sort*** return strnatcmp ($elem1['1'], $elem2['1']);
});
unset($row); //END natural-order sorting questions by title
foreach ($listQuestionArray as $row) { //loop each question
$thisQuestionID = $row[0];
$thisTitle = trim($row[1]);
$thisURL = trim($row[2]);
$thisVersionDate = trim($row[3]);
$thisFrequency = trim($row[4]); //6/17/2014
$thisClauseType = trim($row[6]); //10/10/2014
$thisAlternate = trim($row[7]); //2/9/2015
$RequireDepartment = ""; //6/17/2014 START new tbl structure
if ($thisClauseType=="YELLOW") { //10/10/2014
$sqlgetdept = "select RequireDepartment from far_yellowDept where QuestionID='$thisQuestionID'";
} else {
$sqlgetdept = "select RequireDepartment from far_questionsDept where QuestionID='$thisQuestionID'";
} //10/10/2014
$resultgd = mysql_query($sqlgetdept, $dbconnection);
if (!$resultgd) {
echo 'Could not run query [6]: ' . mysql_error();
exit;
}
while ($rowgd = mysql_fetch_array($resultgd)) {
$RequireDepartment .= $rowgd[0] . ", ";
}
unset ($rowgd);
unset ($resultgd);
//$RequireDepartment = trim($row[5]);
//$thisFrequency = trim($row[6]); //6/17/2014 END
$curClauseInfo = ""; //9/15/2014 temp string for Clause info
$curClauseInfo .= "<td class=resultTbl bgcolor=#d9e0e4><a class='rptnav' href='" .$thisURL. "' target=new>" . $thisTitle . "</a>";
if ($thisVersionDate!="" && $thisVersionDate != NULL) {
$curClauseInfo .= "<BR>(" .$thisVersionDate. ")";
}
if ($thisAlternate!="" && $thisAlternate != NULL) { //2/9/2015
$curClauseInfo .= "<BR><BR>" .$thisAlternate;
}
$curStatusStr = ""; //9/15/2014 temp string to store current status for each dept for current FARS clause
$chkQuestion = true; //assume this question is compliance.
foreach ($deptList as $EachDept) { //loop each dept
if (strpos($RequireDepartment, $EachDept) !== false) { //if this question is required for current dept
$curStatusStr .= "<td class=resultTbl nowrap align=center>";
if ($thisClauseType=="YELLOW") { //10/10/2014
//12/11/2014 fetch approval status for YELLOW clause from new table
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else { //if NO approval response is found
$curStatusStr .= "Approval<BR>Required";
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
$chkQuestion=false;
} else { //10/10/2014 for clause type = CERTIFY and GREEN
//check for approval
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7b]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else {
//get latest response per each question
$sql2 = "select * from far_responses where QuestionID=$thisQuestionID and Department='{$EachDept}' order by ResponseDate desc limit 1";
$result2 = mysql_query($sql2, $dbconnection);
if (!$result2) {
echo 'Could not run query [8]: ' . mysql_error();
exit;
}
$num_rows2 = mysql_num_rows($result2);
if ($num_rows2>0) { //if response is found
$row2 = mysql_fetch_array($result2);
$thisResponse = $row2[2];
$thisResponseBy = $row2[5];
$thisResponseDate = $row2[6];
$tempResponseDate = str_replace(" ", "<BR>", $thisResponseDate); //6/12/2014 show time on next line
$curStatusStr .= "<B>". $thisResponse . "</B><BR>" . $thisResponseBy . "<BR>" . $tempResponseDate;
if ($thisResponse=="YES") { //if latest response is YES, check if it has expired or not
/* 6/2/2014 Disable this function - no need to check Frequency as all answers will be reset on 1/1
$chkDate = strtotime($thisResponseDate);
$chkDate = strtotime("+$thisFrequency day", $chkDate);
if (time() > $chkDate) {
print "<font color=red><BR>Expired</font>";
$chkQuestion=false;
}
6/2/2014 */
} else { //PENDING or EXPIRED
$chkQuestion=false;
}
} else { //no previous submission
$curStatusStr .= "Response<BR>Pending";
$chkQuestion=false;
}
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
} //10/10/2014
} else { //this question does not apply to current dept
$curStatusStr .= "<td class=resultTbl align=center>N/A</td>";
}
}
$curStatusBox = ""; //9/15/2014 temp string to store green/red icon
$curStatusBox .= "<td class=resultTbl align=center bgcolor=#d9f1fe>";
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") { //4/15/2015; 1/6/2015 Contract has been submitted
$sqlFreezeStat = "select LightIndicator from far_contract_clauses where ContractID='$thisID' and QuestionID='$thisQuestionID'";
$resultFreezeStat = mysql_query($sqlFreezeStat, $dbconnection);
if (!$resultFreezeStat) {
echo 'Could not run query [10]: ' . mysql_error();
exit;
}
$num_rowsFS = mysql_num_rows($resultFreezeStat);
if ($num_rowsFS>0) { //if response is found
$rowFS = mysql_fetch_array($resultFreezeStat);
switch ($rowFS[0]) {
case "GREEN": $curStatusBox .= "<img src='images/greenicon.gif' width='20'>"; break;
case "YELLOW": $curStatusBox .= "<img src='images/yellowicon.gif' width='20'>"; break;
case "RED": $curStatusBox .= "<img src='images/redicon.gif' width='20'>"; break;
default: $curStatusBox .= "Status is not being frozen for this record";
}
} else { $curStatusBox .= "Status is not being frozen for this record"; }
unset ($resultFreezeStat);
} else { //1/6/2015: Not submitted - so shows real-time light status
if ((int)$chkQuestion==1) {
$curStatusBox .= "<img src='images/greenicon.gif' width='20'>";
//9/15/2014 Latest Audit Info
/* 12/11/2014 hide audit *** (if want to add it back, need to add fancybox script ***
$sqlchkAudit = "select AuditDate from far_audit where QuestionID=$thisQuestionID order by AuditDate Desc limit 1";
$resultA = mysql_query($sqlchkAudit, $dbconnection);
if (!$resultA) {
echo 'Could not run query [9]: ' . mysql_error();
exit;
}
$num_rowsA = mysql_num_rows($resultA);
if ($num_rowsA >0) { //if response is found
$rowA = mysql_fetch_array($resultA);
$AuditDateTemp = $rowA[0];
$AuditDateSplit = explode(" ", $AuditDateTemp);
$AuditDate = "<a class=\"fancybox\" href=\"audithistory.php?ID=" .$thisQuestionID. "\">" .$AuditDateSplit[0]. "</a>";
//$AuditDate = $AuditDateSplit[0];
} else {
$AuditDate = "N/A";
}
$curClauseInfo .= "<BR><BR>Last Audit: " . $AuditDate;
if($_SESSION['UserAccessLevel']=="FULLAUDIT") //9/15/2014 new access level AUDIT rights
$curClauseInfo .= "<BR>Auditor: <a class=\"fancybox\" href=\"audit.php?ID=" .$thisQuestionID. "\">Audit It</a></td>";
else
$curClauseInfo .= "</td>";
hide audit*** */
} elseif ($thisClauseType=="YELLOW") { //10/10/2014
$curStatusBox .= "<img src='images/yellowicon.gif' width='20'>";
$curClauseInfo .= "</td>";
} else {
$curStatusBox .= "<img src='images/redicon.gif' width='20'>";
$curClauseInfo .= "</td>";
}
}
$curStatusBox .= "</td>";
print "<tr>"; //9/15/2014 Print out new temp strings
print $curClauseInfo;
print $curStatusBox;
print $curStatusStr;
print "</tr>";
}
echo "</table></div>"; //10/15/2014 closing DIV, added document ready
?>
<SCRIPT type="text/javascript">
$(document).ready(function () {
$('#options table').floatThead({
//the pageTop is a global function i have here, it takes care of making the table float under my floated nav
scrollingTop: pageTop,
useAbsolutePositioning: false
});
});
</SCRIPT> <!--10/15/2014 END -->
<?php
}
?>
It's smaller and cleaner and the file_get_contents() can get the job done. But you always need to make sure you have the html of the page.

Cross referenced tables from multi-dimensional arrays php?

How do it turn a multidimensional array like:
$fruits['apples']['blue'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['apple']['red'] = 34;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
into a cross referenced table like:
alt text http://1updesign.org/uploads/p24.png
$cols = array('blue', 'red', 'orange');
echo '<table>';
echo '<thead><tr><td></td><th scope="col">' . implode('</th><th scope="col">', $cols) . '</th></tr></thead>';
echo '<tbody>';
foreach($fruits as $label => $row)
{
echo '<tr>';
echo '<th scope="row">' . $label . '</th>';
foreach($cols as $k)
{
echo '<td>' . (isset($row[$k]) ? $row[$k] : 0) . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
You’ll want some HTML escaping and such, but that’s the gist of it.
Your array is bad designed. How should one know, that apples is the same as apple. Your array should be constructed this way:
$fruits['apples']['blue'] = 24;
$fruits['apples']['read'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
Then iterating is easy. The first level of the array are the rows. So:
<?php
$column_head = array();
foreach($fruits as $key => $value) {
$column_head = array_merge($column_head, array_keys($value));
}
$column_head = array_unique($column_head);
print_r($column_head);
?>
<table>
<tr>
<th></th>
<?php foreach($column_head as $head): ?>
<th><?php echo $head; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($fruits as $fruit => $amount): ?>
<tr>
<td><?php echo $fruit ?></td>
<?php foreach($column_head as $head): ?>
<td><?php echo isset($amount[$head]) ? $amount[$head] : 0 ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This generates which columns to use on fly, but it can be hardcoded which might be easier. As the code uses a lot loops it might be not that efficient...

Pattern in while loop

<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
How do I make a pattern for the background color? For ex, grey, blue, grey blue.
There are multiple ways of doing this. Here is one.
<table>
<?php $i = 0; ?>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr<?php echo (++$i & 1 == 1) ? ' class="odd"' : '' ?>>
<td>
<?php echo $row['test'] . " " . ' ($' . $row['test2'] . ") ?><br>
</td>
</tr>
<?php endwhile; ?>
</table>
I suggest giving a CSS class (I've called it "odd" here) to every second row rather than both odd and even. Then you just do:
tr td { background: grey; }
tr.odd td { background: blue; }
in CSS.
You need something like a state variable, where you store wheter the last row was blue or grey. Then you print out the other color and update the state variable for the next pass.
This is one example:
<?php
echo '<table>';
$state = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
if( $state%2 == 0 )
echo '<td style="background-color:grey;">';
else
echo '<td style="background-color:blue;">';
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
echo '</td></tr>';
$state++;
}
echo '</table>';
?>
If it's a 2 colour pattern, use a variable to switch between blue and grey. if more than 2 colours, use a rotating counter
2 colours
$blue = true;
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td color="<?php echo $blue?'blue':'grey'; $blue ^= true; ?>">
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
More than 2 colours, the general solution:
$colourIndex = 0;
$colours = ('blue', 'red', 'green');
...
...
<td color="<?php echo $colours[$colourIndex]; $colourIndex = ($colourIndex+1)%length($colours); ?>">
You can also use the InfiniteIterator to repeat the sequence again and again. This, like the "rotating counter", works for an arbitrary amount of elements.
$props = new InfiniteIterator(
new ArrayIterator(array('a', 'b', 'c','d', 'e'))
); $props->rewind();
$l = rand(10, 20); // or whatever
for ($i=0; $i<$l; $i++) {
$p = $props->current(); $props->next();
echo 'class="', $p, '"... ';
}

Categories