Changing input format and database issue - php

I'm tasked with fixing a job information page at work. When someone clicks "edit job" to edit a job, a form of all the database titles and values is listed and they can click on an input box and change it and update. Basic stuff.
Now, in the input box for "Payment terms:" the percentages are written exactly like this, "40/40/20" and so in the database under payment they're listed as 40/40/20.
So the label + input box looks like this, Payment terms: [40/40/20].
<p><label for='payment'>Payment Terms</label><input name='payment'
id='payment' value='<?php if(isset($data2['payment'])) echo
$data2['payment']; ?>' /></p>
I want to change this to 4 drop down boxes where they can pick the percentages, for instance
Payment terms: [40]
[40]
[20]
[empty]
There is a TON of jobs with their own payment terms in the db and I think I may have to add 4 columns to the db instead of just 1 column named payment and values listed as %/%/%/%.
Obviously that doesn't seem like a good solution as it would take forever to fix all the jobs and enter their data for each term into the new columns.
What should I do ?

You can use explode to split the string from your database. Then you can make 4 <select> boxes:
<?php
$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) { ?>
<select>
<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>
<?php } ?>
I put the blank option first as it will be selected by default that way.

Related

What is the best way to write the code that sum the values of checkbox choices

I would like to have a form that enables a user to choose the vehicles. The user should get the total price of his choice. I wrote this little script, and it works properly. I am just curious is there a better way to do it. For example, there are a lot of IFs in foreach loop. What if I have, for instance, 100 checkboxes. Should I automate that in a way that for every new type of vehicle the script should make new IF statement? That sounds awkward. Is there a way to put a number of prices directly in checkbox form or something? However, what would be the best way to do such a thing. Thanx.
if (isset($_POST['submit'])){
$automobils=$_POST['auto'];
$set= array();
echo "You ordered: " ;
foreach ($automobils as $model){
if ($model == "chevrolet"){
$set[]=20000;
}
if ($model == "reno"){
$set[]=15000;
}
if ($model == "punto"){
$set[]=10000;
}
echo "<i>$model </i>";
}
$sum = array_sum($set);
echo "</br> Whole price is $sum $";
}
?>
<form action="" method="post">
<input type="checkbox" name="auto[]" value="chevrolet"/> Chevrolet</br>
<input type="checkbox" name="auto[]" value="reno"/> Reno</br>
<input type="checkbox" name="auto[]" value="punto"/> Punto</br>
<input type="submit" name="submit" value="Submit"/>
</form>
Well without adding a database and a whole another level of fun programming.
You can do this with an explode command (And really shrinks your foreach as well)
on the input value
value="chevrolet"
Change to something like
value="chevrolet;20000"
then in your foreach loop
foreach ($automobils as $model){
$eachmodel = explode(";",$model);
$set[] = $eachmodel[1];
}
Ideally you'd store your possible values, and their corresponding prices, in a database, rather than in your code. But here's a quick solution, involving an associative array acting as a map between each vehicle and its price.
$map = [
'chevrolet' => 20000,
'reno' => 15000,
'punto' => 10000
];
if (!empty($_POST['auto']) {
echo 'You ordered:<br />';
$total = 0;
foreach($_POST['auto'] as $model)
if (array_key_exists($model, $map)) {
echo ' - '.$model.'<br />';
$total += $map[$model];
}
echo 'Total price: '.$total.'<br />';
}
Then, you just update the map as you add/change vehicles/prices etc.
Note it's key to store the allowed values/prices code-side (or in a DB) rather than in your form as the latter is editable via the DOM, so you'd need something server-side to validate it anyway.
If you want to put number in checkbox. You can put it with value by using some special separator.
For example
<input type="checkbox" name="auto[]" value="punto_20000"/> Punto</br>
Later you can use Explode string and can get value for selected.

Dealing with starting index in array - PHP

I've got an array of users from a database (I'm working in PHP, using CodeIgniter in Sublime)
I've got a view, that has a select that show display all the users, so in my view, at the top, I have this code (suppose that the arrays has 3 items):
<?php
$optionsUsers = array();
$qtyUsers = count($users); -->
if($qtyUsers > 0){
$optionsUsers[0]['name'] = 'Choose an option';
for($i=0; $i < $qtyUsers; $i++){
$optionsUsers[$i]['id'] = $users[$i]["userId"];
$optionsUsers[$i]['name'] = $users[$i]["username"];
}
}
?>
Then, in the select part, I have this:
<select id="cursadaUsuario">
<?php
$qtyOptionsUsers = count($optionsUsers);
if($qtyOptionsUsers>0){
for($i=0; $i<$qtyOptionsUsers; $i++){
if($i == 0){
echo '<option value="0" disabled selected>Please select an option</option>';
}else{
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
}
}else{
echo '<option value="">There are no options available</option>';
}
?>
</select>
I've assigned to the $optionsUsers array in [0] the string "Choose an option" because when iterating THAT ARRAY in the select, I wanted to display it as disabled and just iterate the rest of the elements as usual
The problem is that array $users starts in 0 --> I've checked it with a foreach and all the users display are actually there:
foreach ($users as $key => $value){
print_r($users);
});
But I wanted [0] to be the text to display, "Choose your option", so if I assign the text to [0], the first item in array $users is never shown :( (in this example, it would iterate the text and 2 of the items, not the 3)
If I remove the text to [O], and just iterate the array, all the users are shown correctly, no one is missing, but that means... no text to tell "Choose an option" :/
I would like it to look like this --> http://www.hkvstore.com/phpreportmaker/doc/images/dropdownselect.png, so I want the text "Choose you option" to be shown AND disabled, and then the elements of the array, in my case, a list of users.
Note: I would like to keep using a 'for' loop.
Note2: This (Add option selected disabled in PHP) would be kind of similar to what I want to achieve, but still, I don't think I could just change the keys and assign my own to a list of users, the could be changed, added, deleted, etc.. :/
Ideas? Thanks in advance! :)
Unless I'm not understanding you, it's the same as the "No options available" option – it belongs outside the loop:
if ($qtyOptionsUsers > 0) {
echo '<option value="0" disabled selected>Please select an option</option>';
for ($i = 0; $i < $qtyOptionsUsers; $i++) {
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
} else {
echo '<option value="">There are no options available</option>';
}
you need to push the users data from index 1 rather than from 0 index.Try below code to fix the choose option
for($i=0; $i <= $qtyUsers; $i++){
$optionsUsers[$i+1]['id'] = $users[$i]["userId"];
$optionsUsers[$i+1]['name'] = $users[$i]["username"];
}

input (radio) value consists of ~2000 bytes, is there a better way?

I have a MySQL database that stores items (goods and services), and along with each item, terms (terms and conditions) will also be stored, which can be roughly 2000 bytes.
http://i.imgur.com/7t3cvSE.png
This is my basic set up
$term_options = array();
$term_options[] = "None";
$term_options[] = "massive string containing 2000 bytes or more";
...
foreach ($term_options as $term) {
?>
<label class="term">
<input type="radio" name="terms" value="<?php echo $term; ?>">
<?php echo $term; ?>
</label>
<?php
}
The above code does exactly what I want, but it feels wrong to have a massive value within a radio input (which may contain Unicode characters). Am I wrong to worry?
Before, I used a SELECT menu with option values equal to the index position of each array item:
?>
<select name="terms">
<?php
$i = 0;
for ($i = 0; $i < count($term_options); $i++) {
?>
<option><?php echo $i; ?></option>
<?php
}
?>
</select>
<?php
Then my $_POST would look something like this:
$terms = $term_options[$_POST['terms']];
It worked nicely until it came to my update form which should display the currently selected values. I wasn't sure how to compare the isset value with something generated via array.
It's simple to do this with static values, e.g.:
<option <?php if (isset($row['x']) && $row['x'] === 'x') echo 'selected'; ?>>x</option>
but while creating each option in a foreach loop, I have no idea what to do and the below doesn't work:
<option <?php if (isset($row['x']) && $row['x'] === $term_options[$i]) echo 'selected'; ?>><?php echo $i; ?></option>
$i++;
Yes, you are right in your worries. If this page is going to display many of these items and each item has a massive string like this, the final page is going to be huge. An this page will be sent by your server to the client browser. Bigger the page, bigger the time.
You are retrieving these items from a MySQL database. Each item probably has a primary key. Why don't you just use this primary key as part of the name of the radio buttons and then you may retrieve again just the selected item?
Something like
<input type="radio" name="rb_1">
where this "1" appended to "rb_" is the key of an item. Then you just need to break this string, recover the primary key and search if to recover the huge string.
This may generate another database operation, of course. But this will be nothing when compared with the transmission of a huge page with, say, 100 times 2k items.

Should I create another table column or is there another way I can go about doing this?

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

booking form:Price change on selecting different option from dropdown list - PHP and Javascript

I have online hotel booking system script, where the room prices and room types are pulled out from the database using php. I only have 2 rooms in this system. One accommodates up to 4 people, the other one up to 6.
The booking form has From and To dates, Type of room (x suite), which can be selected from 0 to 1, followed by price x 120 per room per night. I also have an option to select number of People. There is set price of 120 per room per night for up to 2 people. For every additional person 20 is added to the price. so if there is 3 people in suite, the price would be 140. I tried to make it work myself, but i just cannot make the price change according to number of people selected.
The code for select tag for people is as follows:
<select name="people" class="FormFields" onChange="checkBookingForm()" style="width:70px">
<?php for ($i=1; $i<=$SETTINGS["room_people"]; $i++) {
if ($i==$_REQUEST["people"]) {
$selected='selected';
}
else {
$selected='';
}
?>
<option value="<?php echo $i; ?>" <?php echo $selected; ?>><?php echo $i; ?></option>
<?php }; ?>
</select>
The function checkBookingForm() deals with text change when a particular room is selected and it will show the number of people this room accommodates. the function is here:
<script language="javascript" type="text/javascript">
function checkBookingForm() {
var allRooms=new Array();
var totalPeople = 0;
for(i=0; i<document.NewBookingFrm.elements.length; i++) {
if(document.NewBookingFrm.elements[i].type=="select-one") {
name_t = document.NewBookingFrm.elements[i].name;
if (name_t!=='people') {
value_t = document.NewBookingFrm.elements[i].value;
totalPeople = parseInt(allRooms[name_t]) * parseInt(value_t) + totalPeople;
}
}
}
if (totalPeople==1) {
var acP = 'person';
} else {
var acP = 'people';
};
if (totalPeople!=document.NewBookingFrm.people.value) {
totalPeople = '<strong style="color:red; font-size:14px">'+totalPeople+'</strong>'
}
document.getElementById('PeopleAccommodate').innerHTML = 'selected room(s) can accommodate ' + totalPeople + ' ' + acP;
}
I have tried different things, but as I am learning Javascript at the same time, I am not getting anywhere. I am still trying to understand how DOm works. If anybody can point me to the right direction it would be really appreciated. I understand what I have to do with the code:
check first how many people are
selected
then check if any of the
rooms is selected (if value is 1)
and if one room is selected then
increase the price accordingly or
decrease it.
for number of available rooms I currently have this code:
<select name="room_<?php echo ReadFromDB($row["id"]); ?>" class="FormFields" onChange="checkBookingForm()" style="width:70px">
<option value="0">0</option>
<?php for ($i=1; $i<=$available_rooms; $i++) {
if ($i==$booked_rooms["quantity"]) $selected=' selected'; else $selected='';
?>
<option value="<?php echo $i; ?>"<?php echo $selected; ?>><?php echo $i; ?></option>
<?php }; ?>
</select>
x
">
the link to a more complete code: http://jsfiddle.net/x6ZYB/
well you mix php and html in an unusual way
you should use heredoc for a better code maybe?
well you shouldnt post the php code
there are many errors
hm why not trying to fetch with jquery and .value() the value of the inputs when they are clicked and change the price with .html() ?
well the code is a mess for me
do you have a html output of this as an example?
and also the div where the price is written that is calculated?

Categories