So I have this table filled with a row (we call it $numbers for now) containing numbers greater than 100 000. For example 581 249
I want to echo these values on-screen (using PHP) with a MySql query. Only do I want to divide the returned value by 1000...
The idea is this:
I have made a horizontal bar which is the length of $numbers. But the width of this bar is the value of $numbers in pixels... Basically, it creates a bar with a with of (for example) 581 249 pixels :') ...
This is obviously not the goal. So I have chosen to divide this value by 1k. In this way, the bar fits better on-screen.
How do I implement this in my MySql query?
The echo code for the query is this:
if(isset($_POST['submit'])){
$jaar = $_POST['year'];
echo "<CENTER><h1>".$_POST['year']."</h1></CENTER>";
$result2 = mysql_query("SELECT week, SUM(numbers), SUM(orders) FROM productie WHERE year =" . $year . " GROUP BY week");
while($row=mysql_fetch_array($result2) or die(mysql_error())){
echo "<div class='BarTable'>
<table>
<tr>
<td><div class='BarLabel''>".$row['week']."</div></td>
<td class='BarFull'>
<img src='images/bargraph/month_bar.png' height='12' alt='320' width=".$row['SUM(numbers)']." />
<p>".$row['SUM(numbers)']."</p>
</td>
</tr>
</table>
This while loop goes trough the database, and creates a new bar for every new week found in the database. In this way my result is a nice horizontal bar graph with all the weeks (with the corresponding $numbers) under eachother.
The only problem I'm still facing (as said before), isi that the bars are way too wide. Now I want to decrease the size, but still keep the entered value (since the value of $numbers is displayed behind the bar).
How to divide this value by 1000?
Without mentioning that you should be using PDO or mysqli for new projects, I think what you're looking for is this:
SELECT week, ROUND(SUM(numbers)/1000) as thousandths, SUM(orders) ...
And then access it in your array with $row['thousandths']
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I can only use one page and have to use PHP and html in order to make a table using a for loop to increment three different columns. The first column is 'Rate' the second is 'Annual Interest' and the third is 'Monthly Interest'
PURPOSE: Practice in writing calculations and loops and in embedding
HTML inside a PHP tag
PROCEDURE: In this lab you will write a php program that will
calculate the annual and monthly interest on a loan. There will be no
HTML page and no form. The program will use a loop to calculate the
annual and monthly interest rate on 50000 dollars for every interest
rate from 1 to 10 ( 1 being 1% APR (annual percentage rate). Format
the results to display dollar signs and two decimal places. Display
all the data in an HTML table (see provided jpeg). The code must have
variables for the interest rate, annual interest and monthly interest
and must define a constant named AMOUNT that will have a value of
50000.
Annual interest on a loan is calculated by multiplying the loan amount
by the annual interest rate (expressed as a decimal – if the annual
Interest rate is 1 percent the formula will multiply 50000 by .01.
Monthly interest can be calculated by dividing the annual interest by
12. Write a program that will calculate the annual and monthly interest for $50,000 at annual rates from 1 to 10 percent in
increments of 1 percent and output the results as a table. You may use
any type of loop you choose.
HINTS: The first few lines in the php tag will declare your
variables. To create a table, you use echo statements and place the
HTML inside of single quotes. For example, this code, inside a php
tag, will create and display a paragraph element:
echo 'Hello World!';
You will need to indicate the start of a table outside your loop. You
will create the first row of the table outside the loop. The rest of
the rows will be created inside of a loop that uses a counter going
from 1 to 10. Inside each iteration the loop you will calculate the
annual and monthly interest on 50000 using the counter, storing the
answers in your variables and displaying the info in a row of the
table. The ending tag for the table will be after the loop.
Provide a CSS file that will at a minimum will format the table.
Yea, it's a class assignment and unfortunately the class only meets once per week and the professor doesn't really specialize in this subject matter, but a recent surge in enrollment has stretched the faculty kinda thin and she's virtually unavailable. We've only had two classes thus far, and I'm still pretty new to PHP.
*************EDIT*************
<!--Indicates page is HTML5 compliant-->
<!DOCTYPE html>
<html>
<head>
<!--Titles the page at the top such as on the browser tab (w/ Chrome)-->
<title>Monthly & Yearly Interest</title>
<!--Pulls the CSS styling from the main.css page-->
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<main>
<p>Yearly and Monthly Interest for $50,000 at Varying Rates</p>
<table border="1">
<tr><td>Rate</td><td>Annual Interest</td><td>Monthly Interest</td></tr>
<?php
$Ammount = 50000;
$Percent = 1;
$Annual= 500;
$Monthly = $Ammount * $Percent/12;
for ($counter = 1; $counter <= 10; $counter++) {
echo "<td>$Percent%</td><td>$$Annual</td><td>$$Monthly</td>";
$Percent++;
$Annual+=500;
//$Monthly = ;
echo "<tr></tr>";
}
?>
</table>
</main>
</body>
</html>
I've updated my code and cleaned it up. Thank you for all the help. I'm still having an issue with this though. I've tried using $Annual = number_format(500,2); and also modified the increment counter below the echo to do likewise, but I can only get the number formatting to appear on the first row. Also having a similar issue with the $Percent value. Technically I need the percent value to be 0.01 for the $Monthly calculation to be correct, but I need the $Percent value to appear as a whole digit in the first column. I'm trying my best to explain this clearly. I have to use a for loop and have to follow the above instructions in order to create this:
When you're doing string concatenation in PHP you need to use . (dot) operator.
echo "<td>"$percent.'%'"</td>";
must be written as
echo "<td>".$percent."%</td>"; or echo "<td>$percent%</td>";
also for loop consists of 3 part
for (init counter; test counter; increment counter) {
code to be executed;
}
if you want only test counter, you can use it as
for (;$percent <= 10;) {
echo "<td>$percent%</td>";
$percent++
}
or
for ($percent = 1 ; $percent <= 10; $percent++) {
echo "<td>$percent%</td>";
}
HTML table roughly consists of 3 parts
<table>
<tr>
<td>
</td>
<tr>
</table>
You have missed the <tr>
the syntax should look like
<table border="1">
<?php
$percent = 1;
for($percent = 1; $percent < 10; $percent++)
{
echo "<tr><td> $percent % </td></tr>";
}
?>
</table>
or if u want to use your
for ($percent <= 10) {
echo "<td>"$percent.'%'"</td>";
$percent++;
}
use while instead
<?php
$percent = 1;
while($percent <= 10)
{
echo "<tr><td> $percent % </td></tr>";
$percent++;
}
?>
so I am trying to figure out a way with php to say if a users rank is the highest, then put a picture next to their name. I can do it for a specific user but I am not sure how to do it for the highest rank
<td>
<?php if($r->rank=='3') {
echo '<img src="image.jpg">';
}?>
</td>
Well first of all you have to determine what the highest rank is so it will start like
I'm assuming you want one star per user thats on the page or something of sorts
$star_given = false;
foreach($foo as $bar) {
echo "<tr><td>";
echo ($star_given===false ? $bar->rank >= 3 ? : "<div style='background: url(img/foo.png) no-repeat' : " ");
echo "</td>
}
This is not catering for if more than one person has the highest rating though e.g
$personA->rank = 3;
$personB->rank = 2;
$personC->rank = 3;
in this case you would just remove the $star_given property and just let it check for the rank
edit
Sorry seem to have to misunderstood your question;
You would simply add a variable called
$highest_rating=0;
Before the loop. Then when someone becomes the highest rating you simply go like $highest_rating = $r->rank. Then after the Loop you can echo the highest Rating , or alternitavly you can use JS for this.
Here is a small script showing you how to access tables
JSBIN
I am trying to create an html table using php and mysql to track the number of items which have reached certain stages in a multi-stage process. I need to display the names of the stages as a slanted header row (already sorted that with css3, blank column as first) and each row will have the name of the type of item in the first cell, followed by the count of items at each stage in the appropriate columns.
The stages have a numerical value so a simple array is fine - but there are 16 possible stages and this has to be query-driven as different people will see different stages.
The types of item vary according to another relationship (anything from one to 614 types at this time) but I have a query that tells me the distinct name to display on each row and a code for the type of item.
My code produces a horizontal header with the sixteen stages (plus an extra cell at the start to allow for the vertical legend)
The rows of data start with the legend cell but somehow the loops are then giving me 32 cells per row (help please). The results I expect are in the 1st, 3rd etc. There is no code that should deliver an extra blank as I put a zero for no match. So here it is:
// a previous $sql query checks for the distinct types of item in the batch in the table with joins to two other tables that accord with the two components of the CategoryCode
$today=date('H:i:s d-m-Y');
$categs=array();
while($row=mysql_fetch_assoc($result)){
$categs[$row['CategoryCode']]=$row['description'];
}
$headrow='';// sets variable for the header row
ed to
$bodyrow='';// sets variable for the body rows
$sql="SELECT stage_id, short_stage_desc FROM process_stages WHERE stage_omit='0' ORDER By showord"; // for various historic reasons the stages do not follow a 1,2,3 pathway so this query needs a showord column to produce some logic
$result = mysql_query($sql);
$cou=mysql_num_rows($result);
$stages=array(); // sets up array to check against
$s='1';
while($row=mysql_fetch_assoc($result)){
$s++; $ccolor = ($s % 2) ? "odd" : "even"; //for css background cell colour and the mix of div and spans that follow are part of doing 45 degree slanted column headings
$stageid=$row['stage_id']; $stagedesc=$row['short_stage_desc'];
$headrow.="<th class='skew'><div class='$ccolor'><span>$stagedesc</span></div></th>";
$stages[]=$row['stage_id']; //puts stages in display order
}
$headrow.="</tr></thead><tbody>";
//Now for the table bodyy
foreach($categs AS $key=>$category_descript){
$bodyrow.="<tr><td class='item-cat'>$category_descript</td>";//produces first cell as label
$sql="SELECT process_stage, COUNT(DISTINCT RowID) AS itemcount FROM item_detail WHERE CategoryCode='$key' GROUP BY process_stage";
$result=mysql_query($sql);
$gothro=array(); //will hold the key for the stage and number of items at that stage
while($row=mysql_fetch_assoc($result)){
$stag=$row['process_stage'];
$gothro[$stag]=$row['itemcount']; // fills array
}
$s='1';
reset($stages); // just ensure the array pointer is at start
foreach($stages AS $stagval){
$s++; $ccolor = ($s % 2) ? "odd" : "even"; // css for body row
if(array_key_exists($stagval,$gothro)){$bodyrow.="<td class='$ccolor'>".$gothro[$stagval]."<td>";}else{$bodyrow.="<td class='$ccolor'>0<td>";}
}
$bodyrow.='</tr>';
}
$outs="<br /><br /><div class='item-table-container'>
<h4>$bnam Situation at $today</h4>
<div class='item-table'>
<table><caption>$batch_description</caption><thead><tr><th>Item Type</th>$headrow.$bodyrow<tbody></table> </div></div> ";
Looks like you missed a forward slash in a closing td tag here:
... else{$bodyrow.="<td class='$ccolor'>0<td>";}
I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:
//Add Flair Containers as needed
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
It prints correctly, where content = $flair1, $flair2, and so on.
<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>
But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?
Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.
Like so:
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
if (empty($flairCode)) continue;
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
I suspect that you could simply prepend if($flairCode) to your echo statement. That would make your inner loop:
foreach($flair as $flairCode){
if($flairCode) echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
Some points to note:
Since the $flair array will always be the same, construct it outside of the loop (this will let you evaluate the condition only once too.
Using $fQty++ is not enough to guarantee unique ID's, especially since every time it hits the while the value is reset. I suggest $fQty should not be part of the while condition and simply stay as an independent tally.
Stop using double-quotes. They're slow.
I got an XML file being echoed by PHP and all the code works fine but my problem is that inside a tag (exam and the attribute is chapter which is what's being echoed) there's more than one tag (ex, that's what is being echoed as exam #) and I am echoing the data to a table and I want it to display it like this:
| Chapter 1 | Chapter 2 |
|--Exam 1---|--Exam 1---|
|--Exam 2---|--Exam 2---|
| Chapter 3 | Chapter 4 |
|--Exam 1---|--Exam 1---|
But What I am getting is something like this: (I know why though)
| Chapter 1 |
|--Exam 1---|
| Chapter 1 |
|--Exam 2---|
| Chapter 2 |
|--Exam 1---|
It keeps on repeating the tag's attribute and I know why, because I am echoing the tag's attribute that I have as a variable in a table data. So the question is not why it is happening but how can I change it to display it the way I want it.
I guess maybe there's a way to delete the attribute if there's more than one (I know you can delete it but I don't know how to show it once and delete the others)
The code that I have is something like this:
In XML
<maintag>
<exam chapter="Chapter 1">
<ex id="1">Exam 1</ex>
<ex id="2">Exam 2</ex>
<ex id="3">Exam 3</ex>
</exam>
<exam chapter="Chapter 2">
<ex id="4">Exam 1</ex>
<ex id="5">Exam 2</ex>
</exam>
<exam chapter="Chapter 3">
<ex id="6">Exam 1</ex>
</exam>
<exam chapter="Chapter 4">
<ex id="7">Exam 1</ex>
<ex id="8">Exam 2</ex>
<ex id="9">Exam 3</ex>
<ex id="10">Exam 4</ex>
</exam>
</maintag>
The PHP
<?php
$xml = DOMDocument::load('examdata.xml');
$xpath = new DOMXPath($xml);
$exams = $xpath->query('//exam/ex');
$istyle = 1; //This is to add gray after every other row
echo " <table cellpadding=\"0\" cellspacing=\"3\" border=\"0\" width=\"60%\" align=\"center\">
<tr id=\"center\" bgcolor=\"#999\">
<td>Book</td>
<td>Exam</td>
<td>ID</td>
<td>Student's Exam Status</td>
</tr>
";
foreach($exams as $exams2) {
$chapter = $exams2->parentNode->getAttribute('chapter');
$examid = $exams2->getAttribute('id');
$examname = $exams2->nodeValue;
if ($examid < 5) { //where it says 5 there goes a php variable where it has the queried user's exam number from the database, again this is all finished no need to change this.
$exstatus = "You already took this exam.";
}elseif ($examid == 5) {
$exstatus = "This is your exam (exam link)";
}elseif ($examid > 5) {
$exstatus = "You are not yet on this exam";
}
echo "<tr id=\"center\"";
if ($istyle % 2 == 0)
echo " bgcolor=\"#ccc\"";
echo ">
<td>$chapter</td>
<td>$examname</td>
<td>$examid</td>
<td>$exstatus</td>
</tr>";
$istyle++;
}
echo "
</table>";
?>
Notice that the table structure is different than the way I said I want it and I was getting it above, I just changed it because I couldn't leave it the way it was.
Note that what I want to change is where it says chapter, I want it to display it once and below it to display exam 1 and below that exam2 ect. and next to the chapter put the next chapter (in this case chapter 2) and below that exam 1 and below that exam 2 ect. and after that create another table row below exam 2 and put two other chapters and below that the other exams.
Notice that the exams do not follow a pattern and this is an edited version of the file since there's hundreds of those and the values are different of what you see above.
The code above works, I just want to modify it so it could meet my requirements.
I've figured it out, it took me hours but I finally did it.
This is the code I used for the PHP, the XML stayed the same. I'll try to be as detailed as possible so it could help anyone with a similar problem or so they could extract info from it and modify it to their needs.
<?php
//self explanatory
$xml = DOMDocument::load('examdata.xml');
//again, self explanatory
$xpath = new DOMXPath($xml);
//looks for ex under exam in the xml I loaded above xml
$exams = $xpath->query('//exam/ex');
//I just put a number for testing purposes but it actually gets the user's exam id from the database
$studentexnum = "5";
//column counter, will be used to tell that after every 2 chapters, break the table data (td) and table row (tr) and create a new one
$_2chapters = 1;
//Opens the table and displays it to the client
echo "<table cellpadding=\"5\" cellspacing=\"5\" border=\"0\" width=\"25%\" align=\"center\">
<tr>"; //Opens the first table row and end the echoing
//starts the loop, for every exam, makes exam2 same as exam
foreach($exams as $exams2) {
//looks at my xml file for the tag ex (what I defined above) and gets the attribute called chapter from his parent (the tag above it)
$chapter = $exams2->parentNode->getAttribute('chapter');
//gets the attribute called id from the tag ex
$examid = $exams2->getAttribute('id');
//makes the tag ex a string so we could display it
$examname = $exams2->nodeValue;
////////////////////////////////////////Now for the Fun Part/////////////////////////////////////////////////////////////////////////////////
//conditional statement saying that if the variable chapter2 is set, display the conditions below, if it's not set (which is not when its starts the loop) do something else
if (isset($chapter2)){
//says if variable chapter defined above is equal to variable chapter 2 which is defined below do something. This is not true the first time but it is the rest of the loop, even is is a million.
if ($chapter == $chapter2) {
//variable chaptertd (which is called below) will equal to nothing if chapter equals to chapter2, this will happen at every exam (every ex tag in my xml file which is in the question above)
//this will avoid having repeated chapter, ie: chapter1 - exam one, chapter1 - exam 2, chapter1 exam 3, ect. will make it chapter 1, exam 1, exam 2, exam 3, ect
$chaptertd = "";
//if chapter does not equal to chapter2
}else {
//here we increment variable _2chapters that was 1 above, now is two, this is necessary so it could display two chapters side by side and break right before the third chapter, this will happen later
$_2chapters++;
$chapter2 = $chapter; //THIS PART IS EDITED, BUT NECESSARY
//Now we give a value to variable chaptertd, it was nothing before because I didn't want to repeat the title every time the loop found a new tag ex from my xml. This will only happen once in every chapter
$chaptertd = "
</td>
<td align=\"center\" valign=\"top\">$chapter2";//here we create the html that variable chaptertd will be displaying after a new name from the attribute chapter is found. This will display the name of the chapter to our table
}
//this else will only happen the first time the loop runs since only the first time is when the variable chapter2 is not defined, after this runs the variable chapter2 will have been defined
}else {
//chapter2 will be the same as chapter, if chapter equals to the string chapter1 so will chapter2.
$chapter2 = $chapter;
//here we create the same td as above since we want to display the name of the chapter the fist time it runs, if we don't do this the first chapter won't be display to the client
$chaptertd = "
<td align=\"center\" valign=\"top\">$chapter2";
}
//This part you don't have to concern yourself with it, I made this because I needed it to display different info depending whether the user was allow to see that exam.
//the variable examval is defined outside this code, that's on my html code which would do nothing here since it uses javascript and css. this gets the attribute id from our ex tag.
if ($examid < $studentexnum) {
$exval = "lessthan";
}elseif ($examid == 5) {
$exval = "equalto";
}elseif ($examid > 5) {
$exval = "greaterthan";
}
//here we say what happens when the variable _2chapters reaches the third attribute called chapter. we say if the remainder of variable _2chapters divided by 3 equals 0 do something
//else do nothing since we didn't define the else because we didn't needed it. this part will only happen at every third chapter, it will break from the previous chapter thus making
//it a new row right under the values of the tag ex which is under chapter 1 the third time the loops runs, but this will happen infinite amounts of time, after that it will be under
//chapter 3 and after that chapter 5 and so on.
if ($_2chapters % 3 == 0) {
//here we reset the count back to one because if we don't and there's more than one tag ex under chapter 3, it will be braking after every ex
$_2chapters = 1;
//here we echo the break from the previous chapter
echo "
</td>
</tr>
<tr id=\"center\">";
}
//here we echo the variable chaptertd which we gave different values to above depending whether the chapter's name has been declared already or not. If it has been declared, chaptertd
//won't show anything, if the chapter has never been declared it will create a new td and display the chapter's name and after that it will become nothing again
echo "$chaptertd<br />
$examname";//here we show the client what's the name of the exams under the given chapter, there could be one or one hundred of this and it will only display the chapter once and will display the rest
//of the exam names one after the other
//here we say that chapter2 equals to chapter, this way chapter2 will equal to the name of that loop, if the next time it repeats there's a new chapter the value of chapter will change
//thus making this statement false above and that will force it to create a new td with the new name until another name appears.
$chapter2 = $chapter;
}
//close the table to have a well formatted html file to display to the client.
echo "
</td>
</tr>
</table>";
?>
I actually figured it out a while ago, but this "smart forum" doesn't allow me to answer my OWN question before 8 hours because I don't have enough points or something. It's like as if it was trying to say that because I am new here I am dumb and can't find the solution to my problem on my own inside 8 hours. So I went to sleep. I just wanted to help other people that might come to this post in the future and hopefully the answer would answer some of their questions.
You probably meant...
foreach($exams as $exam)
...to get an item from the array, instead of...
foreach($exams as $exams)
BTW i would think of other names for the variables exam and ex, use names that describes what they are, maybe exam and chapter.