Multiple Form Dropdown Form, Validation, PHP - php

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>

Related

Unit Converter PHP

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>

How to make an entry in a text box required when one specific radio button is selected?

I have several radio buttons which can be chosen and then the form can be sent without an issue. However a user can easily select the "Other" radio button and submit without giving any context or reason on why they chose it leaving the people receiving the "completed" form guessing what the issue is.
What I want to happen is that if a person selects the "Other" radio button and try and submit without a note/message/comment they will be interrupted with a requirement massage.
The snippet of the form that I want this to happen to is:
<label>
<input name="category" type="radio" value="Other" checked>Other
</label><br><br><br>
Note: <br> <textarea name="comment" rows="10" cols="70" placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly">
I have tried many variations of if statements and the required function given with HTML5 but can not seem to get what I need.
Any help will be appreciated and thanks in advance.
Edit 1:
Here is the full code of my form:
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form>
Edit 2:
Here is the full code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/main_style.css">
<style>
.error {color: #FF0000;}
table, th, td {border: 1px solid white;}
</style>
</head>
<body>
<script>
function close_window() {
close();
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include("includes/classes.php");
include("includes/classes_monitoring.php");
$link = open_v8_db();
$users = get_clocked_in_users();
$OperationID = #$_REQUEST['OperationID'];
$title = "";
$grayedOut = false;
$disabledInput = "";
$hiddenJobDiv = "";
$hiddenPartDiv = "";
$ID = "";
$html = "";
$jobid = #$_REQUEST['JobID'];
$part_id = #$_REQUEST['PartID'];
$machCode = #$_REQUEST['Machine'];
if ($OperationID == 20)
{
$title = "Punching Machine";
$grayedOut = true;
}
elseif ($OperationID == 30)
{
$title = "Folding Machine";
$grayedOut = true;
}
elseif ($OperationID == 40 || $OperationID == 140)
{
$title = "Powder Coating";
$grayedOut = true;
}
elseif ($OperationID == 50 || $OperationID == 150)
{
$title = "Assembly";
$grayedOut = true;
}
elseif ($OperationID == 60 || $OperationID == 160)
{
$title = "Inspection";
$grayedOut = true;
}
elseif ($jobid != "" && $part_id == "")
{
$title = "Job";
$OperationID = 70;
}
else
{
$title = "General";
$OperationID = 80;
$grayedOut = false;
}
if ($greyedOut = true)
{
$disabledInput = "readonly";
}
function customErr($ID)
{
$html = "";
$issueReport_folder = 'document/Production System/';
$issueReporting = $issueReport_folder.'IssueReporting.csv';
$file_handle = fopen($issueReporting, "r");
if ($ID == 20)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Punch")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 30)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Fold")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 40 || $ID == 140)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Powder")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 50 || $ID == 150)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Assembly")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 60 || $ID == 160)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Inspectoin")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 70)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Job")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 80)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "General")
{
$html[] = $line_of_text[1];
}
}
}
fclose($file_handle);
return $html;
}
$jobErr = $partErr = $machErr = "";
$job = $part = $mach = $note = "";
if ($jobid == "")
{
$hiddenJobDiv = "style=\"display:none;";
}
if ($part_id == "")
{
$hiddenPartDiv = "style=\"display:none;";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="reportForm">
<h2>Report <u><?php echo $title; ?></u> Error</h2>
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form> <!-- End of form. -->
</div>
</body>
</html>
you can't use required method like that. I think your solution is add dynamically textbox when user clicked the option button like that:
Add this javascript function in your file:
<script language="javascript">
function activateNote()
{
var i = 1;
note_div.innerHTML = "Note: <br> <textarea required id='comment' name='comment' rows='10' cols='70' placeholder='More detail... (Is there a way to recreate the error? What happened?)' ></textarea><br><br>"
}
</script>
Change your elements like that, "delete note textarea" than add div element:
<label>
<input onClick="activateNote()" type="radio" name="category" value="Other">Other
</label>
<div id="note_div"></div>
One possible solution is to conditionally add the required HTML5 attribute to the required field when the "Other" radio button is selected.
You can do this with a javascript method attached to your radio button that is (de/)activated on select.

php export data to cvs

I need a help exporting search query by clicking on export button. I am able to get data from database to the browser. However, when I click on export button, it refreshes the page, and doesnt do anything.
I am new to php and and programming. Any help will be appreciated :)
<?php
include('dbcon.php');
?>
<form id="searchform" action="index.php" method="post">
<table>
<tr>
<td class="searchleftcol"><h3>Service:</h3></td>
<td>
<select id="service" name="service" class="searchoption">
<option value="">-- Select Service Name --</option>
<?php
$resultservice = mysqli_query($con,"Select * from services") ?>
<?php
while ($line = mysqli_fetch_array($resultservice)) {
?>
<option value="<?php echo $line['serviceid'];?>"> <?php echo $line['service'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Environment:</h3>
</td>
<td>
<select id="environment" name="environment" class="searchoption">
<option value="">-- Select Environment --</option>
<?php
$resultdomain = mysqli_query($con,"Select * from evn") ?>
<?php
while ($line = mysqli_fetch_array($resultdomain)) {
?>
<option value="<?php echo $line['envid'];?>"> <?php echo $line['env'];?> </option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<h3>Status:</h3>
</td>
<td>
<select name="status" class="searchoption">
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
</td>
</tr>
</table>
<input type="reset" name="reset">
<input type="submit" name="submit" value="Search">
<input type="submit" name="export" value="Export" />
</ul>
</form>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
// Here I erased code that displays data from MySQL.
if (isset($_POST['export'])) {
if (empty($_POST['service'])) {
echo "Please select service in dropdown" . "</br>";
}
else {
$service = $_POST['service'];
}
if (empty($_POST['environment'])) {
echo "Please select Environment in dropdown" . "</br>";
}
else {
$env = $_POST['environment'];
}
if ((!empty($service)) && (!empty($env))) {
$sql="SELECT * from servers";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$mydata = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($mydata);
//Programetically get the Headings of the excel columns
$columns_total = mysqli_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$contents .= '"'.$heading.'",';
}
$contents .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$contents.='"'.$row["$i"].'",';
}
$contents.="\n";
}
// Remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
Header("Content-Disposition: attachment; filename=ProductsReport".date('d-m-Y').".csv");
print $contents;
}
}
mysqli_close($con);
}
?>}
Thanks,
Ray

PHP sticky forms dropdown and checkboxes

I'm writing a php form and I can't get the drop down boxes and check boxes to stick as in when I fill in my details but don't click something it will keep everything else filled but that one part that wasn't filled out. I can do it for the input text and radio buttons but I can't get it done for drop downs and checkboxes
<!DOCTYPE html>
<style>
#import url(stickyTextInput.css);
</style>
<?php
if(isset($_REQUEST["left"]))
{
process_form();
}
else
{
display_form_page('');
}
?>
<?php
function display_form_page($error)
{
$self =$_SERVER['PHP_SELF'];
$first_name = isset($_REQUEST['name']) ? $_REQUEST['name']:'';
$last_name = isset($_REQUEST['lastname']) ? $_REQUEST['lastname']:'';
$age = isset($_REQUEST['age']) ? $_REQUEST['age']:'';
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']: '';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head>
<title>
Forms Sticky input
</title>
<style>
#import url(stickyTextInput.css);
</style>
<style type="text/css">
.error
{
color:#ff0000
}
</style>
</head>
<body>
<?php
if($error)
{
echo "<p>$error</p>\n";
}
?>
<form action= "<?php echo $self?>" method = "post">
<h1>Forms-Sticky Input</h1>
<label>First Name:</label>
<input type="text" size="10" maxlength="40" name="name" value = "<?php echo $first_name?>">
<br>
<label>Last Name:</label>
<input type="text" size="10" maxlength="40" name="lastname" value = "<?php echo $last_name?>">
<br>
<label>Age:</label>
<input type="text" name="age" size="10" value="<?php echo $age?>">
<br>
<label>Gender</label>
<input type="radio" name="gender" value="male" <?php check($gender, "male")?>>Male
<input type="radio" name="gender" value="female" <?php check ($gender, "female")?>>Female
<br>
<label>Select favourite Colour</label>
<select name= "color">
<option <?php checkradio($color, "Red")?>>Red
<option <?php checkradio($color, "Blue")?>>Blue
<option <?php checkradio($color, "Green")?>>Green
<option <?php checkradio($color, "Pink")?>>Pink
<option selected="selected" disabled="disabled">
</select>
<br>
<label>Food</label>
<input type="checkbox" name="food[]" value="beans" <?php checkbox ($food, "beans")?>>Beans
<input type="checkbox" name="food[]" value="crisps" <?php checkbox ($food, "crisps")?>>Crisps
<input type="checkbox" name="food[]" value="lemons" <?php checkbox ($food, "lemons")?>>Lemons
<br>
<div id="buttons">
<input type="submit" name="left" id="left" value="Submit" >
<input type="reset" name="right" id="right" value="Reset" >
</div>
</form>
</body>
</html>
<?php
}
?>
<?php
// If $group has the value $val then select this list item
function check($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function checkradio($group, $val)
{
if ($group === $val)
{
echo 'selected = "selected"';
}
}
?>
<?php
// If $group has the value $val then select this list item
function checkbox($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function process_form()
{
$error = validate_form();
if($error)
{
display_form_page($error);
}
else
{
display_output_page();
}
}
?>
<?php
function validate_form()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
$error = '';
$reg_exp = '/^[a-zA-Z\-\']+$/';
$reg_exp1 = '[0-9]{3}';
if(!preg_match($reg_exp, $first_name))
{
$error .= "<span class=\"error\">First Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!preg_match($reg_exp, $last_name))
{
$error .= "<span class=\"error\">Last Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!is_numeric($age))
{
$error .= "<span class=\"error\">Age is invalid (numbers only)</span><br>";
}
if (strlen($gender) == 0)
{
$error .= "<span class=\"error\">Select Male/Female</span><br>";
}
if (strlen($color) == 0)
{
$error .= "<span class=\"error\">Select one color</span><br>";
}
if (! is_array($food))
{
$error .= "<span class=\"error\">You must select one food</span><br>";
}
return $error;
}
?>
<?php
function display_output_page()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head><title>Form Results</title></head>
<body>
<h1>Form Results</h1>
<?php
echo " First Name: $first_name<br/>\n";
echo " Last Name: $last_name<br/>\n";
echo " Age: $age<br/>\n";
echo " Gender: $gender<br/>\n";
echo " Favourite Color: $color<br/>\n";
echo "<ul>";
if (is_array($food))
{
echo "Favourite Food is:";
foreach($food as $selection)
{
echo "<li>$selection</li>";
}
}
echo "</ul>";
?>
</body>
</html>
<?php
}
?>
Possibly a browser issue, however most browsers only require 'checked' at the end of the html input element for checkboxes. However you appear to be outputting checked = "checked" This is possibly the problem. Have a look at the sample below:
<?php
$name = isset($_GET['name']) ? $_GET['name'] : '';
$agree = isset($_GET['agree']) ? 'checked' : '';
$title = isset($_GET['title']) ? $_GET['title'] : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="name" id="name" value="<?=$name;?>">
<input type="checkbox" name="agree" id="agree" <?=$agree;?>>
<select name="title" id="title">
<option value="Mr" <?=$title == 'Mr' ? 'selected' : ''?>>Mr</option>
<option value="Mrs" <?=$title == 'Mrs' ? 'selected' : ''?>>Mrs</option>
<option value="Miss" <?=$title == 'Miss' ? 'selected' : ''?>>Miss</option>
</select>
<button type="submit">submit</button>
</form>
</body>
</html>
After processing the values the output html should be as follows:
<form action="">
<input type="text" name="name" id="name" value="test">
<input type="checkbox" name="agree" id="agree" checked>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss" selected>Miss</option>
</select>
<button type="submit">submit</button>
</form>

Editing Checkboxes, radios, and dropdowns

I found this site providing code for creating, reading, updating and deleting. I am confused about how to add checkboxes, radio buttons, and dropdowns
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I'm not concerned with the pagination at all——my primary concern is to be able to put in two dropdowns, yes/no radio button, and a collection of 3 checkboxes using PHP.
My attempts were useless as when I tried to edit choices the values did not stay. Included are my three files: pets, editpets, and view.(I changed the file name for database, etc.)
<?php
function renderForm($first, $last, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>New Customer</title>
</head>
<body>
<?php
// display possible errors
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name:</strong> <input type="text" name="firstname" value="<?php echo
$first; ?>" />
<strong>Last Name:</strong> <input align="center" type="text" name="lastname" value="<
?php echo $last; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<br/>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<input style="color:purple;" type="submit" name="submit" value="Create My Order :-)">
</div>
</form>
<center>Click Here for Orders</center>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if my form submits and, upon triumph, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, check its validity
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check to make sure everything is filled!
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, show the form again
renderForm($firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("INSERT customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years'")
or die(mysql_error());
// once saved, redirect to cheview page
header("Location: view.php");
}
}
else
// if the form is not submitted, show my form again.
{
renderForm('','','','','','','');
}
?>
<?php
$types = array("Cats", "Dogs", "Others");
function renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: </strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br/>
<strong>Last Name: </strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<br /><br />
<input type="submit" name="submit" value="Resubmit My Order :-)">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// check for id being an integer
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM customers WHERE id='$id' ")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$pets = $row['pets'];
$size = $row['size'];
$type = serialize($row['type']);
$years = $row['years'];
// show form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View customer orders</title>
</head>
<body>
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM customers")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Pets</th>
<th>Size</th>
<th>Type</th>
<th>Years</th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['pets'] . '</td>';
echo '<td>' . $row['size'] . '</td>';
echo '<td>' . $row['type']. '</td>';
echo '<td>' . $row['years'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
I'm honestly lost at this point. I've been working on this for an entire month and I have no idea what I'm doing any more. I'd be so thankful if anyone can help me to edit this to work.
Thanks everyone.
Right, to get your saved results from the database I'm sure you're aware of how to do this.
For your radio buttons you're going to want to select your 'size' value from the database and use an if statement to determine which radio button will be 'checked'
forename/surname is a matter of simply getting the forename/surname from database and setting the appropriate input tags to the acquired values
You've already posted a technique for handling the combo/drop-down boxes
you'd perform a similar process for the 'type' checkboxes, compare your database values to the values of your checkbox input tags and if the value matches, set the checkbox to checked.
Next time please be more specific in what you are asking for help with and separate your code into segments that correspond with the files it is contained in.
if you have 3 files, have a code block for each file.

Categories