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++;
}
?>
Related
I have a list of places to visit in the boat tours I organise, the tour locations of which can change occasionally, including the price for each. So I have found a way to populate the list of possible locations and accommodation and other possible costs, so that I can quickly compute the total costs for each custom tour, with a simple checkbox (the checkbox for the customer to decide which places to visit or stay at). The entrance fees and hotel etc costs for most places are per person, but some are per boat, such as the case of beer, or a van transfer of the group to their final destination. In such cases the charge for each location ($priceofspot) would not be multiplied by the number of people in the group ($ppl). I guess this should be inserted in some sort of While loop or something? I have no idea which direction to go to resolve this, even some basic pointers would be greatly appreciated, thank you.
if(in_array($place,$spotsarray)) {
print "<input name='spots[]' value='".$place."' type='checkbox' checked='checked' /> ".$place." - ".$priceofspot."<br>";
if (($place='Case of beer') OR ($place='Van Transfer Sibaltan'))
{$totalspotcost=$totalspotcost+$priceofspot;}
else {$totalspotcost=$totalspotcost+($priceofspot*$ppl);}
}
else print "<input name='spots[]' value='".$place."' type='checkbox' /> ".$place." - ".$priceofspot."<br>";
If I understand the problem correctly you want to do a checkbox list and calculate the total. You can do this with switch if you want to.
<?php
for($i = 0; $i < count($places_selected); $i++){
if(array_key_exists($places_selected[$i], $ppl_multiplie_list){
// Multiplie people normally
$people = $ppl_count;
// Given input from user.
}
else{
// People = 1
$people = 1;
}
switch($places_selected[$i]){
case 'Case of beer':
$total_price = $total_price + $spot_price['Case of beer'] * $people;
// Or instead of $spot_price array just enter a price.
break;
}
}
echo 'Your total is :' . $total_price;
Didn't understand the response from kyc and doesn't include the checkboxes etc, so I decided a more simple solution would be just to create different tables:
one where the total price per spot multiplies by the number of people (most of the spots);
one where the total price per spot is just the price per spot (since the cost is per boat, such as one complimentary case of beer, not per person);
and one where the total price per spot multiplies by the number of days of the tour, such as if they want to rent a kayak or wakeboard etc.
i have this code:
<tr><td>Data expirare:</td><td><?=date_chooser("date",date("Y-m-d"),0)?></td></tr>
It is working properly, but at the moment I look from 1920 until 2050 and I want to show me only of certain pending and the next five years.
I assume you are using the date_chooser() algorithm from this SO post: How to jump to anchor on submit - not to top of page or this internet page: http://ideone.com/Ab0cLD
I adapted a small part of the code by adding two variables: $from_year and $to_year. They do now define the range of the years in your drop down. You can the adapt the value of the variables to your needs.
$chooser.="<select name='".$name."year'>";
$from_year = 1950
$to_year = date("Y") + 5
for($i=$from_year;$i<=$to_year;$i++)
{
if($i==$year) $selected='selected';
else $selected='';
$chooser.="<option $selected>$i</option>";
}
I'm having an issue trying to figure out how to solve this problem.
I have a database with a Table that holds job information. There's a column called "Payments" and the values % per payment term are split up here like so: http://i.imgur.com/Y2Lb48e.png
So at the bottom the values will read 40%, 40%, 20%.
In the form, these values are displayed exactly the same as in the database, 40/40/20.
I was tasked with creating 4 option boxes instead with values in each ranging from 10% to 100%. Here's what the code looks like.
<label for='payment'>Payment Terms</label>
<?php
// Create 4 % boxes that add up to %100 for Payment Terms
// Must validate and add up to %100
$selects = 4;
if (isset($data2['payment'])) {
$percentages = explode("/", $data2['payment']);
// Make sure that the array is long enough by adding zeroes to the end
while (count($percentages) < $selects) $percentages[] = 0;
}
else {
$percentages = array_fill(0, $selects, 0);
}
$options = range(10, 100, 10);
for ($i = 0; $i < $selects; ++$i) { ?>
<ul style="list-style-type: none;"><li><select id="paymentSelect">
<option></option>
<?php foreach ($options as $o) { ?>
<option value="<?php echo $i; ?>"
<?php if ($o == $percentages[$i]) echo ' selected="selected"'; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select></li></ul>
<?php } ?>
This is what the form looks like now: http://i.imgur.com/2OvDtsn.png
The blue date boxes is what I want to create. Will I have to make a new column in my table? How will I link each percentage to each date since the percentages are already in the table?
You could make a new table in your data base "Payments" and have a foreign key to tie it back to the original table, your payment column and your date column. Then you can have as many payment percents and Dates you would ever want.
I might be tempted to future proof this for 10 options or 20 options or whatever to save always changing the columns in the table. How about you have 4 rows to show your payment terms - pairs for each date and %. If you have multiple possibilities - i.e. several clients with different payment terms then your table should have a client_id. This way you can have some clients with 2 payments, others with 50 - simply by adding rows with fields (client_id, %, date).
Validation is the same and the table much simpler. To retrieve the payment data you are fetching multiple rows that make table building from PHP fairly straightforward too.
Best
Nick
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']
I am trying to use the progress bar for a non-traditional purpose. I want to use the functionality to display a horizontal bar graph of two values retrieved from a database.
My PHP/MySQL/JQuery:
// retrieve results for display
$query = mysql_query(" SELECT furniture_purchases, electronics_purchases FROM sales WHERE store_id = $storeId ");
$sales = mysql_fetch_array($query);
$furniture = $ratings[0];
$electronics = $ratings[1];
echo ("<script type='text/javascript'>
// display sales results
$(document).ready(function() {
$('div.furnitureBar').progressbar({ value: $furniture });
$('div.electronicsBar').progressbar({ value: $electronics });
});
</script>");
My HTML:
<div class='furnitureBar'></div>
<div class='electronicsBar'></div>
Now the problem is, say if 101 furniture items were sold, the progress bar for furniture will fill the entire space since 100 is the max value according to JQuery progressbar documentation: http://jqueryui.com/demos/progressbar/
Instead I want the two values to form dynamically as comparison to one another, so if 101 furniture items were sold and 90 electronics items were sold, then both bars should be in the middle instead of it seeming like 100 is the max number of sales possible. In fact there is no limit to the max number of sales.
I hope I make sense.
You need to scale the values so they fit. Example:
$furniture = $ratings[0];
$electronics = $ratings[1];
$max = max($furniture, $electronics);
if ($max > 100){
$furniture *= (100 / $max);
$electronics *= (100 / $max);
}
This example determines whether one of the numbers is greater than 100, which would result in an overflow (for the progressbar). If it is, it calculates a ratio such that the highest number is now 100. Then, it adjusts the second number accordingly. If you need an integer value, simply round or apply an (int) cast to the values.
The math behind it:
Let's say $furniture is 104 and $electronics is 76. As you have pointed out, 104 won't work because jQuery UI progress bars only support values up to 100.
104 is greater than 76, so we calculate the ratio to adjust the values like this: 100/104 = 0.961538462. So;
0.961538462 * 104 = 100
0.961538462 * 76 = (rounded) 73
This is actually very easily done with tables that are filled to your desired percentage. Performance-wise, it'll beat the pants off the Jquery option.
An example from a site I did:
<td>
<div id="graph_grey">
<div id="graph_self" style="width:62%;"></div>
</div>
</td>