Running a form with incomplete/empty values - php

I'm writing a script that calculates the total distance, in miles, traveled on a trip. It needs to calculate the total distance, and the distance between any midpoints. Right now it calculates the total distance fine. I am using drop-boxes, and have allowed to it accept up to 5 midpoints. Now, I may just be trying to make this more complicated than it needs to be but...
I'd like to be able to run the script even if three of the midpoint forms are left empty (which would just say "Select City" with a value of " " or null). Is there a way I can have the script run when the three fields of the form are left empty??
EDIT: Each 'index' or 'pont' is defined with a = " ";. I'm using a multidimentional array for the whole script and the 7 drop boxes start with a selected value of "Select City" which has an empty/null value. I just want to know how to run the form/script when two of the mid-point values/drop boxes are left with the initial value of "Select City".
Sorry, here is some of my code:
<?php
if (isset($_POST['Submit'])) {
$StartIndex = stripslashes($_POST['Start']);
$EndIndex = stripslashes($_POST['End']);
if (isset($Distances[$StartIndex][$EndIndex]))
echo "Total trip distance from $StartIndex to $EndIndex is". $Distances[$StartIndex][$EndIndex]." miles<br/>";
else
echo "Distance could not be calculated";
}
?>
This is where I'm stopped at...
<?php
if (isset($_POST['Submit'])) {
$Point1 = stripslashes($_POST['1']);
?>
^^the other four midpoints are the same, I have zero clue how to still run the form when only the start city, end city, and two mid-point cities are selected. I'd add the whole script but it very long with the multidimensional array
To see what my form looks like you can go to >> 131.118.95.215/users/mjswiontek0/project/city/citytocity.php

Just evaluate your test (e.g. empty($_POST["1"])) on every midpoint to find, if you want to include it into calculation.
See commented (very generic) example:
if (isset($_POST['Submit']))
{
// start with the start index
$PrevIndex = stripslashes($_POST['Start']);
$Point = 1;
$Distance = 0;
do
{
// do we have the N-th midpoint?
$HavePoint = !empty($_POST[$Point]);
// if not, use end point
$NextIndex = stripslashes($_POST[$HavePoint ? $Point : 'End']);
// add distance between the two midpoint to total
$Distance += $Distances[$PrevIndex][$NextIndex];
// make current point the previous point to the next iteration
$PrevIndex = $NextIndex;
// move to the next point for the next iteration
$Point++;
}
while ($HavePoint);
}

Related

PHP: Separate Area Code from Phone number with MySQL Database

I want to separate the area code from a phone number string by using a area code mysql database.
For example the string is 0349152023.
The endresult should be 03491 52023.
To get the endresult, i want to split the string and search every digit in database.
For example 0 and then 3 and then 4 and then take the last found result.
The code i have at the moment is only to prepare the phone number string for futher actions:
$phone1 = preg_replace('/[oO]/', '0', $phone-string);
$phone2 = preg_replace("/[^0-9]/", "", $phone1);
Then i use str_split to cut the string in pieces:
$searchArray = str_split($phone2);
Thanks for your help.
You may build an array containing all the area codes.
Then you may write something like this:
foreach ($area_codes as $code) {
if (substr($phone, 0, strlen($code)) == $code) {
$phone_string = substr($phone, 0, strlen($code))." ".substr($phone, strlen($code));
}
}
You can obviously add a controller in order to verify if the area code was found or not.
step 1: select all area codes from db and put them into an array $areaCodes
step 2: iterate over $areaCodes as $code and check if the phonenumber starts with $code. if it does, create a string that has a whitespace between the code and the rest of the number
$phonenumber = '0349152023';
$preparedPhonenumber = '';
foreach($areaCodes as $code){
if(str_pos($phonenumber, $code) === 0){
// phonenumber starts with areacode
$phoneWithoutCode = substr($phonenumber, strlen($code));
$preparedPhonenumber = $code.' '.$phoneWithoutCode;
break;
}
}
// if one of the areaCodes was 0349,
// the variable $preparedPhonenumber is now '0349 152023'
edit: you can shorten the amount of returned area codes from db by selecting only those that start with a certain string.
Let's assume the shortest area code in germany is 3 digits long (which i think is correct).
$threeDigits = substr($phonenumber,0,3);
$query = "SELECT * from areacodes
WHERE code like '".$threeDigits."%'
ORDER BY CHAR_LENGTH(code) DESC";
this will drastically shrink down the probable area codes array, therefore making the script faster.
edit 2: added order by clause in query so the above code will check for longer areacodes first. (the break; in the foreach loop is now obligatory!)
Hi Leonardo Gugliotti and Cashbee
i sort the areaCodes to get a better match. The php scripts works fine, but takes to long time to handle 5000 MySQL entries. Is it possible to make the foreach search directly in mySQL?
<?php
$sample_area_codes = array( '0350', '034', '034915', '03491', '0348', '0349', '03491', '034916', '034917',);
sort($sample_area_codes);
$phone_string = '0349152023';
foreach ($sample_area_codes as $code) {
$subString = substr($phone_string, 0, strlen($code));
if ($subString == $code) {
$phone = $subString." ".substr($phone_string, strlen($code));
}
}
if (!empty($phone)) {
echo $phone;
}
else {
echo "No AreaCode found.";
}
?>
Output: 034915 2023, which is correct
A single probe (assuming INDEX(area_code)):
SELECT ...
FROM AreaCodes
WHERE area_code < ?
ORDER BY area_code DESC
LIMIT 1;
(Where you bind the $phone_number as a string into the ?)
I think you'd better split your database into a tree, making a table for each digit.
So the third digit could refer to the second, the fourth to the third, and so on until you reach the maximum lenght of the prefix. The last table should include the name of the area.
Following your example, supposing that the maximum lenght of the area code was five digits, the fifth_digit_table should have at least four fields like these:
ID
IDref
Number
Name
10 records may have the same IDref, corresponding to the number "2" at the fourth position, linked to the previous "021" through the fourth_digit_table, the three_digit_table and so on; only one among these records, that with the Number field filled with "9", should have the Name "Haan"; the others, if there aren't any, should have the Name "Solingen".
I hope you will manage to speed up your script.

why the Code Does not work

in "$grandtotal1" and "$grandtotal2" does not display the sum
while($data=mysql_fetch_array($hasil)){
$tgl =$data['date_added'];
$jenis_pemilik=$data['pemilik'];
$no_invoice =$data['order_id'];
$pengiriman =$data['shipping_method'];
$berat =$data['weight'];
$namabarang =$data['name'];
$artikel =$data['model'];
$retails =$data['retail']*1;
$odv =$data['odv'];
$ongkir =$data['text'];
$diskon =$data['price']*1;
$harga_jual =$data['harga_jual']*1;
$stars =(($harga_jual-$odv)*80)/100*1;
$grandtotal1 +=($stars);
$divisi =(($harga_jual-$odv)*20)/100*1;
$grandtotal2 +=($divisi);
I apply this code to FPDF does not work , but I apply to html page works
from looking at your code - it seems you want to add 80% of an amount to $grandtotal1 and 20% to $grandtotal 2 - meaning that these are calculations and so the += is appropriate since you want to add numbers rather than concatenate values. I think the issue is that you haven't declared these values intiially so there is nothing to add them to.
before the while loop - declare the values:
$grandtotal1 = 0;
$grandtotal2 = 0;
while($data=mysql_fetch_array($hasil)){....
then when it is time, add the values
$stars =(($harga_jual-$odv)*80)/100*1;
$grandtotal1 +=($stars);
$divisi =(($harga_jual-$odv)*20)/100*1;
$grandtotal2 +=($divisi);
This will add the values of the calculations to each of the $grandTotals. not sure why you are multiplying all values by 1?

Only saving the last entry

I have a form to edit the entrys in the database. With this the staff from my site can change every entry of an movie. It works percetly expect one little thing: It's also possible to change every episode title by iteselfs, and because every movie can have other count of episode, the php has to handle with it. It's working but not the way I want, my code I'm using only take the last entry and save it to the first episode from the movie.
Here is my code.
for ($e = 0; $e < count($_POST["episode"]); $e++) {
$con->query("UPDATE anime_episode SET ep_title = '".$_POST['episode']."' WHERE ep_nr = $e AND ani_id = $a");
}
There can only be one $_POST["episode"]. PHP will group all of the entries into that one variable so count will always return 1. You should try parsing $_POST["episode"] into an array or something first and then counting those elements.

Creating a different array related to different times a loop happens php

there. I'm having a problem with creating arrays in certain conditions in php, i'll try to explain. Here's my code:
for ($i = 1; $i < $tamanho_array_afundamento; $i++) {
if ($array_afundamento[$i] - $array_afundamento[$i - 1] > 1) {
$a = $array_afundamento[$i - 1];
$con->query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
$tabelas_intervalos_afunda1 = ($con->query("SELECT * FROM afunda_$a");
while ($row = $tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC)) {
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
$prevNum = $a;
}
}
So as u can see, i have an if statement in a for loop, what i'm wishing to do is to create
one set of:
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
every time the if statement is runned. I was trying replacing this in the original code:
{
$array_forma_onda_fase1_afund_$a[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_$a[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_$a[] = $row['L3_forma_tensao'];
}
so as $a is changed everytime the if statement is accessed, i could have a different set of these arrays for everytime the if statement is accessed, but php doesn't accept this and i wouldn't have a very good result, though if i can reach it i would be pleased.
But my goal is to get:
{
$array_forma_onda_fase1_afund_1[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_1[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_1[] = $row['L3_forma_tensao'];
}
{
$array_forma_onda_fase1_afund_2[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_2[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_2[] = $row['L3_forma_tensao'];
}
...
where the last number represents the array retrieved for the n-th time the if statement runned. Does someone have a tip for it?
Thanks in advance! Would appreciate any help.
EDIT
As asked, my real world terms is as follows:
I have a table from which i need to take all the data that is inside a given interval. BUT, there's a problem, my data is a sine function whose amplitude may change indefinite times (the data bank is entered by the user) and, when the amplitude goes inside that interval, i need to make some operations like getting the least value achieved while the data was inside that interval and some other parameters, for each interval separately, (That's why i created all those tables.) and count how many times it happpened.
So, in order to make one of the operations, i need an array with the data for each time the databank entered by the user goes in that interval (given by the limits of the create query.).
If i were not clear, just tell me please!
EDIT 2
Here's the image of part of the table i'm working with:
http://postimg.org/image/5vegnk043/
so, when the sine gets inside the interval i need, it can be seen by the L1_RMS column, who accuses it, so it's when i need to get the interval data until it gets outside the interval. But it may happens as many times as this table entered by the user brings it on and we need to bear in mind that i need all the intervals separately to deal with the data of each one.
Physics uh?
You can do what you wanted with the arrays, it's not pretty, but it's possible.
You can dynamically name your arrays with the _$a in the end, Variables variables, such as:
${"array_forma_onda_fase3_afund_" . $a}[] = "fisica é medo";

problem to find out the average

i want to make a CGPA information system for an Educational institute. Say, there have 6 text box, i want to find out the average of 1st 5 text box number as i give input, but if i fill the 1st 4 box of them then also want to find out the average of 1st 4 text box input number and the result is shown in 6th text box position in the same form.i am trying it in another php file, but it doesnt work. the code is here
<?php
$q1 = $_GET['q_1'];
$q2 = $_GET['q_2'];
$q3 = $_GET['q_3'];
$q4 = $_GET['q_4'];
$q5 = $_GET['q_5'];
$x=array($q1,$q2,$q3,$q4,$q5);
$num=count($x);
if($num=4)
{
$sum= $q1+$q2+$q3+$q4;
$num=4;
$avg=$sum/$num;
echo "bestof(4):$avg";
}
elseif($num=5)
{
$sum= $q1+$q2+$q3+$q4+$q5;
$num=5;
$avg=$sum/$num;
echo "bestof(5):$avg";
}
?>
if($num=4)
should really be
if($num==4)
because you want to test for equality and not assign the value 4 to num
when you're initializing $x, it's always going to be size 5. If Question 5 wasn't filled in, your array $x would be ("Answer1", "A2", "A3", "A4", Null).
Try using isset() to determine what ones are filled in from the $_GET array, and then build your array accordingly, for instance:
if(!isset($_GET['q_5']){
$x = array($_GET['q_1'],$_GET['q_2'],$_GET['q_3'],$_GET['q_4']);
}else{
$x = array($_GET['q_1'],$_GET['q_2'],$_GET['q_3'],$_GET['q_4'],$_GET['q_5']);
}

Categories