I am struggling to get my PHP unit converter to work.
I am trying to get multiple converters going but cant seem to get it working.
It'd be great if someone could show me where I'm going wrong and help me get it going. :)
<?php
if($_POST){
$fahrenheit = $_POST['fahrenheit'];
$celsius = ($fahrenheit - 32)*5/9;
}
if($_POST){
$celsius = $_POST['celcius'];
$fahrenheit = ($celcius - 32)*5/9;
}
?>
<form action="" method="post">
Fahrenheit: <input type="text" name="fahrenheit" /><br />
<?php
if(isset($celsius)){
echo "Celsius = ".$celsius;
}
?>
</form>
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
function inches_to_centimeter($given_value)
{
$centimeter=$given_value/2.54;
return $centimeter ;
}
function centimeter_to_inches($given_value)
{
$inches=$given_value*2.54
}
?>
<html>
<head>
<title>Temp. Conv.</title>
</head>
<body>
<form action="" method="post">
<table>
<!-- FAHRENHEIGHT & CELCIUS V -->
<tr>
<td>
<select name="first_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="btn" value="Convert">
</td>
</tr>
<!--FAHRENHEIGHT & CELCIUS ^ -->
<!-- CENTEMETERS & INCHES -->
<tr>
<td>
<select name="first_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<!--CENTEMETERS & INCHES ^-->
<tr>
<td>
<?php
if(isset($_POST['btn']))
{
$first_temp_type_name=$_POST['first_temp_type_name'];
$second_temp_type_name=$_POST['second_temp_type_name'];
$given_value=$_POST['given_value'];
if($first_temp_type_name=='fahrenheit')
{
$celsious=fahrenheit_to_celsius($given_value);
echo "Fahrenheit $given_value = $celsious Celsious";
}
if($first_temp_type_name=='celsius')
{
$fahrenheit=celsius_to_fahrenheit($given_value);
echo "Celsious $given_value = $fahrenheit Fahrenheit";
}
}
if(isset($_POST['btn']))
{
$first_length_type_name=$_POST['first_length_type_name'];
$second_length_type_name=$_POST['second_length_type_name'];
$given_value=$_POST['given_value'];
if($first_length_type_name=='centimeter')
{
$centimeter=centimeter_to_inches($given_value);
echo "Centimeter $given_value = $inches Inches";
}
if($first_length_type_name=='inches')
{
$centimeter=inches_to_centimeter($given_value);
echo "Inches $given_value = $centimeter centimeter";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
I know there is a lot going on, my apologies.
Any help is greatly appreciated :)
Hi please use the following code.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$convertedTemperature = 0;
/* The condition is entered when the request is of POST type. */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$temperature = $_POST['temperature'];
$fromConvertionUnit = $_POST['fromConvertionUnit'];
$toConvertionUnit = $_POST['toConvertionUnit'];
/* if the temperature conversion are of same unit then no need for conversion */
if($fromConvertionUnit == $toConvertionUnit){
$convertedTemperature = $temperature;
}else if($fromConvertionUnit == 'fahrenheit' && $toConvertionUnit == 'celcius') {
/* formula to convert Fahrenheit to Celcius */
$convertedTemperature = ($temperature - 32) * 0.5556;
}else if($fromConvertionUnit == 'celcius' && $toConvertionUnit == 'fahrenheit') {
/* formula to convert Celcius to Fahrenheit */
$convertedTemperature = ($temperature * 1.8) + 32;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div>
<!-- If the temperature value has be submitted and has data then it will prefilled -->
<label for="temperature">Temperature</label> <br/>
<input type="number" name="temperature" id="temperature" value="<?php echo (!empty($temperature)) ? $temperature : '' ?>">
</div>
<div>
<label for="fromConvertionUnit">Select From Convertion Unit</label><br/>
<select name="fromConvertionUnit" id="fromConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<div>
<label for="toConvertionUnit">Select To Convertion Unit</label><br/>
<select name="toConvertionUnit" id="toConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<!-- Once the page is submitted and conversion is done the respective values will be added in the following section -->
<div>
Converted Temperature <b> <?php echo (!empty($temperature)) ? $temperature : '--' ?></b> Value From <b><?php echo (!empty($fromConvertionUnit)) ? $fromConvertionUnit : '--' ?></b> TO <b><?php echo (!empty($toConvertionUnit)) ? $toConvertionUnit : '--' ?></b> is <b><?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '--' ?><b/>
<label for="converted_value">Converted Value</label><br/>
<input type="number" value="<?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '0' ?>">
</div>
<div>
<input type="submit" value="Convert">
</div>
</form>
</body>
</html>
If you want to make a converter, all you need is one input - and a dropdown between what you wish to convert to. Then use a switch in PHP when the form was submitted to check what function you wish to use.
Your current issue is that you overwrite a lot of values, and that you don't check for the right buttons. This is also over-complicating it.
You can further develop this converter by making sure that the input is an actual number - by using filter_var() with a flag that's suitable for your need. You can either validate it or sanitize it, see FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?.
<?php
if (isset($_POST['submit'])) {
switch ($_POST['convert']) {
case "cm-in":
$result = centimeter_to_inches($_POST['value']);
$old_unit = 'cm';
$new_unit = ' inches';
break;
case "in-cm":
$result = inches_to_centimeter($_POST['value']);
$old_unit = ' inches';
$new_unit = 'cm';
break;
case "f-c":
$result = fahrenheit_to_celsius($_POST['value']);
$old_unit = ' Farenheit';
$new_unit = ' Celcius';
break;
case "c-f":
$result = celsius_to_fahrenheit($_POST['value']);
$old_unit = ' Celcius';
$new_unit = ' Farenheit';
break;
}
}
function fahrenheit_to_celsius($given_value) {
return 5/9*($given_value-32);
}
function celsius_to_fahrenheit($given_value) {
return $given_value*9/5+32;
}
function inches_to_centimeter($given_value) {
return $given_value/2.54;
}
function centimeter_to_inches($given_value) {
return $given_value*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Conversions</title>
</head>
<body>
<form method="post">
Convert <input type="text" name="value" /><br />
<select name="convert">
<option value="">--Select one--</option>
<optgroup label="Units of Length">
<option value="cm-in">Centimeter to inches</option>
<option value="in-cm">Inches to centimeter</option>
</optgroup>
<optgroup label="Units of Temperature">
<option value="f-c">Farenheit to Celcius</option>
<option value="c-f">Celcius to Farenheit</option>
</optgroup>
</select>
<input type="submit" name="submit" value="Convert" />
</form>
<?php
if (!empty($result))
echo '<p>'.$_POST['value'].$old_unit.' equals '.$result.$new_unit.'</p>';
?>
</body>
</html>
Related
I have been working on a form that allows entering a menu item for a cafe establishment, alongside its ingredients (arrays of data). Unfortunately, a problem came up as it only executes 1 query even though 2 or more ingredients were entered in the form (dynamic, jQuery).
Here is the PHP code:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$productname = $_POST['product_name'];
$categoryID = $_POST['categoryID'];
$price = $_POST['srp'];
// ingredients
$ingredients = $_POST['ingredients'];
$qty = $_POST['qty'];
$measure = $_POST['measure'];
if (!empty($productname) && !empty($categoryID) && !empty($price) && !empty($ingredients) && !empty($qty) && !empty($measure)) {
for ($i=0; $i < count($ingredients); $i++) {
if ($ingredients[$i] != "" && $qty[$i] != "" && $measure[$i] != "") {
mysqli_query($db, "insert into individual_ingredients values ('', '$productname', '{$ingredients[$i]}', '{$qty[$i]}', '{$measure[$i]}')");
}
}
mysqli_query($db, "insert into end_products values ('', '$productname', '$price', '', '$categoryID')");
mysqli_query($db, "insert into audit_trail values ('', now(), '{$_SESSION['login_user']}', 'New end product added')");
header("location: end_products.php");
} else {
echo '<font color="red">'."Incomplete data entered".'</font>';
}
}
?>
And here is the HTML form and JQuery:
<html>
<head>
<title><?php echo $login_session; ?> | New End Product Record</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//add more fields group
$(".addMore").click(function(){
var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
$('body').find('.fieldGroup:last').after(fieldHTML);
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".fieldGroup").remove();
});
});
</script>
</head>
<body>
HTML form:
<table style="margin: 5% -1% 0 -10%; font-size: 0.9em">
<tr>
<form action="new_end_product_record.php" method="post">
<td>Name</td>
<td><input type="text" name="product_name"></td>
<td>Raw Material/s Used</td>
<td>
<div class="fieldGroup">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
ADD
<br /><br />
</div>
<!-- second set -->
<div class="fieldGroupCopy" style="display: none;">
<div class="input-group">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
REMOVE
<br /><br />
</div>
</div>
</td>
</tr>
<tr>
<td>SRP</td>
<td><input type="text" name="srp"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="categoryID">
<option value="">Select category...</option>
<!--list all categories in the database-->
<?php
$cat_query = "select category_ID, name from end_products_categories";
$get_cats = mysqli_query($db, $cat_query);
while ($option = mysqli_fetch_assoc($get_cats)) { ?>
<option value="<?php echo $option['category_ID']; ?>"><?php echo $option['name']?></option>
<?php } ?>
</select>
</td>
<!-- <td>Expiration</td>
<td><input type="date"></input></td> -->
</tr>
</table><br>
<input type="submit" class="button" name="submit" value="ADD RECORD">
<input type="reset" value="ERASE ALL">
</div></form>
</div>
</body>
</html>
Is there a problem with the loop or with the HTML form that prevents the second to the last set of values from being inserted? Any help would be appreciated.
I'm making a calculator similar to This Calculator
But instead of using Javascript I'm using only HTML and PHP without any kind of scripting, not even CSS.
What happened is that there are 4 text boxes and depending on the choice from the dropdown menu, every time one of those is left empty because the answer will be output which should be in that textbox but I'm echoing the answer and want to disable the box whose value is not needed at that time.
Any help would be appreciated and I know it's a very lousy code but for the time being I just want to add what I described:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Aluminum Pipe - Pressure Rating Calculation </title>
</head>
<body>
<form action="AlPipe.php" method="post">
<div id="new" align="center">
<h2 align="center">Ordering Decimals from Least to Greatest</h2>
<select name="new" align="center">
<option align="center" value="P">Pressure Rating (PR)</option>
<option align="center" value="S">Allowable Stress (S) </option>
<option align="center" value="T">Wall Thickness(T)</option>
<option align="center" value="D">Pipe Outside Diameter(D)</option>
</select>
<p align="center">Allowable Stress(S) =
<input type="text" name="AL" size="5" />
</p>
<p align="center"> Wall Thickness(t) =
<input type="text" name="WT" size="5" />
</p>
<p align="center">Pipe Outside Diameter(D) =
<input type="text" name="POD" size="5"/>
</p>
<p align="center">Pressure Rating(PR) =
<input type="text" name="PR" size="5" />
</p>
<div align="center">
<input type=submit value=Calculate name="Calculate">
<input type=reset value=Reset>
<?php
formula();
function formula()
{
if(isset($_POST['Calculate']))
{
$S=$_POST['AL'];
$T=$_POST['WT'];
$D=$_POST['POD'];
$P=$_POST['PR'];
$cal=$_POST['new'];
}
if($cal=='P')
{
$PR1 = (2 * $S * $T );
$PR2 = $D;
$PR3 = $PR1 / $PR2;
echo "\n Pressure Rating is : ".$PR3;
}
elseif($cal=='S')
{
$S1= ($P * $D) ;
$S2= ($T * 2);
$S3= $S1 / $S2;
echo "\n Allowable Stress is : ".$S3;
}
elseif($cal=='T')
{
$T1 = $P * $D ;
$T2 = 2 * $S;
$T3 = $T1 / $T2;
echo "\nWall Thickness is : ".$T3;
}
elseif($cal=='D')
{
$D1 = 2 * $S * $T / $P ;
echo "\nDiameter is : ".$D1;
}
else
{
echo "Invalid Values";
}
}
?>
</div>
</form>
</div>
</div>
</body>
Does the field need to be disabled after the submit or based on the drop down? Either way you can make the form submit to php and then use something like the following to inject the disabled keyword into your calculator for example you could have a drop down box that has an update button next to it that does the same thing as what follows with the exception it uses the post data from the dropdown to determine what to disable.
<!-- language: lang-php -->
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Aluminum Pipe - Pressure Rating Calculation
</title>
</head>
<body>
<form method="post">
<div id="new" align="center">
<h2 align="center">
Ordering Decimals from Least to Greatest
</h2>
<select name="new" align="center">
<option align="center" value="P">Pressure Rating (PR)</option>
<option align="center" value="S">Allowable Stress (S) </option>
<option align="center" value="T">Wall Thickness(T)</option>
<option align="center" value="D">Pipe Outside Diameter(D)</option>
</select>
<p align="center">
Allowable Stress(S) =
<input type="text" name="AL" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['AL']) && $_POST['WT'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Wall Thickness(t) =
<input type="text" name="WT" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['WT']) && $_POST['WT'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Pipe Outside Diameter(D) =
<input type="text" name="POD" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['POD']) && $_POST['POD'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Pressure Rating(PR) =
<input type="text" name="PR" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['PR']) && $_POST['PR'] == '')) ? 'disabled' : ''; ?> />
</p>
<div align="center">
<input type=submit value=Calculate name="Calculate">
<input type=reset value=Reset>
</div>
</form>
</div>
</div>
</body>
<?php
formula();
function formula()
{
if(isset($_POST['Calculate']))
{
$S=$_POST['AL'];
$T=$_POST['WT'];
$D=$_POST['POD'];
$P=$_POST['PR'];
$cal=$_POST['new'];
}
if($cal=='P')
{
$PR1 = (2 * $S * $T );
$PR2 = $D;
$PR3 = $PR1 / $PR2;
echo "\n Pressure Rating is : ".$PR3;
}
elseif($cal=='S')
{
$S1= ($P * $D) ;
$S2= ($T * 2);
$S3= $S1 / $S2;
echo "\n Allowable Stress is : ".$S3;
}
elseif($cal=='T')
{
$T1 = $P * $D ;
$T2 = 2 * $S;
$T3 = $T1 / $T2;
echo "\nWall Thickness is : ".$T3;
}
elseif($cal=='D')
{
$D1 = 2 * $S * $T / $P ;
echo "\nDiameter is : ".$D1;
}
else
{
echo "Invalid Values";
}
}
?>
I've written this code... but this fails to display text... not sure what's wrong with the code. I'm new to PHP and trying to create a page that gets customer details and puts it in SQL.
<!DOCTYPE html>
<html>
<body>
<?php
$initial="";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
echo "Customer Intial: $initial <br>";
?>
</body>
</html>
Try this:
$initial="";
if(isset($_POST['initial'])){
$initial=htmlentities($_POST['initial']);
}
You correctly sent the POST however you didn't put the value given with the POST into the $initial variable.
<!DOCTYPE html>
<html>
<body>
<?php
$initial = "";
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit"></form>
<br>
<br>
<?php
$initial = filter_input(INPUT_POST, "initial");//GET the input in post method
if ($initial == 1) {
$initial_value = "Mr.";
} elseif ($initial == 2) {
$initial_value = "Mrs.";
} elseif ($initial == 3) {
$initial_value = "Ms.";
} elseif ($initial == 4) {
$initial_value = "M/s";
} else {
$initial_value = "Select initial";
}
echo "Customer Intial: $initial_value <br>";
?>
</body>
</html>
Try,
<form method="post" action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>>
Intials: <select id="cmbInitial" name="initial" onchange="showUser(this.value)">
<option value="0">Select initial</option>
<option value="1">Mr.</option>
<option value="2">Mrs.</option>
<option value="3">Ms.</option>
<option value="4">M/s</option>
</select> <br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<br>
<br>
<?php
if(isset($_POST['initial'])){
$initial=$_POST['initial'];
} else {
$initial = "empty";
}
echo "Customer Intial : ".$initial;
?>
</body>
</html>
I am trying to display the saved data in the database on select before a user can update other choice. I am not really sure how to code it. Can anyone come out with possible solution? Had tried many ways but unable to do so.
Update: I have found out the problem why the options does not show.
This is my code:
`
$consentId = $_GET['consent_id'];
$retrieveConsent = "SELECT * FROM consent, leavetype WHERE consent.type_of_leave = leavetype.type_of_leave";
$retrieveResult = mysqli_query($link, $retrieveConsent) or die("Retrieve Error" . mysqli_error($link));
$queryleavetype = "SELECT * FROM leavetype";
$queryleaveresult = mysqli_query($link, $queryleavetype) or die("Leave Retrieve Error " . mysqli_error($link));
$row = mysqli_fetch_array($retrieveResult);
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Consent </title>
</head>
<body>
<div class="ui-content">
<h3><b>Edit Leave</b></h3>
<form action="doEditConsent.php" method="post" data-ajax="false">
<input type="hidden" name="cId" value="<?php echo $row['consent_id']; ?>"/>
<label for="dateFrom" ><b>Date From:</b></label>
<input type="date" id="dateFrom" name="newDateFrom" value="<?php echo $row['consent_date_from']; ?>" required>
<br>
<label for="dateTo" ><b>Date To:</b></label>
<input type="date" id="dateTo" name="newDateTo" value="<?php echo $row['consent_date_to']; ?>" required>
<br>
<label for="reason" ><b>Leave Type:</b></label>
<select name="leaveType" id="leaveType" data-mini="true">
<?php
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
?>
<option value="<?php echo $rowleave['type_of_leave']; ?>">
<?php echo $rowleave['leave_type']; ?>
</option>
<?php
};
?>
</select>
<br>
<button class="ui-btn ui-corner-all" type="submit" >Submit</button>
</form>
</div>
<?php
}
}
?>
</body>
</html>`
Try this, hopefully it will help you:
<select name="leaveType" id="leaveType" data-mini="true">
<option value=""></option>
<?php
$previous_selected_value = 'previous_selected_value';//get the previous value and assign it to this variable
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
$selected = ($rowleave['type_of_leave'] == $previous_selected_value) ? " selected='selected'" : "";
echo '<option value="'.$rowleave['type_of_leave'].'"'.$selected.'>'.$rowleave['leave_type'].'</option>';
}
?>
</select>
I have this whole code. Jumbled but what I'm trying to do is to have a drop down menu with selections from 1 -10. Then after selecting one, would spit out another form so that if there 3 were selected, would show three rows of fields (name, email). Validation included. What I was first "hard coded" on how many rows of fields to spit out but now what I wanted to do is to have a "selection" in dropdown menu so that the user has the ability to select.... Seem to work but doesn't process. Any PHP expert help? No db, no client-base, no smart alec. If you have time to help please do.
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
// Check if the form has been submitted:
if (isset($_POST['submit'])) {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i+1;
echo $row.": ".$_POST['firstname'][$i]." ".$_POST['lastname'][$i].", ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#",$_POST['firstname'][$i],$body);
$body = str_replace("#lastname#",$_POST['lastname'][$i],$body);
$body = str_replace("#email#",$_POST['email'][$i],$body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<? echo $i.': '; ?><input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
<?php
}
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>
You have to move the second form submit code outside of first form submit. Try this
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
$problem = false; //always try to initialize variables, you may not run into unexpected warnings and problems.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<? echo $i . ': '; ?><input type="text" name="firstname[]" size="20"
value="<?php if (isset($_POST['firstname'][$i])) {
print htmlspecialchars($_POST['firstname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<input type="text" name="lastname[]" size="20"
value="<?php if (isset($_POST['lastname'] [$i])) {
print htmlspecialchars($_POST['lastname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?><input type="text" name="email[]" size="20"
value="<?php if (isset($_POST['email'][$i])) {
print htmlspecialchars($_POST['email'][$i]);
} ?>"/>
</td>
</tr>
<?php } ?>
<tr>
<td><p><input type="submit" class="button" name="submit" value="Register!"/></td>
</tr>
</table>
</form>
<?php
} // moved second for submit to here
elseif (isset($_POST['submit'])) { // Check if the form has been submitted:
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1)) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i + 1;
echo $row . ": " . $_POST['firstname'][$i] . " " . $_POST['lastname'][$i] . ", " . $_POST['email'][$i] . " <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#", $_POST['firstname'][$i], $body);
$body = str_replace("#lastname#", $_POST['lastname'][$i], $body);
$body = str_replace("#email#", $_POST['email'][$i], $body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>