PHP - Can not access the checkbox value that has been checked - php

For my databases project I am doing this form where a user can select the information he wants and it will be displayed on a html page. For the time being I am implementing only the checkboxes where I am encountering a problem.
The problem is that when I check the checkboxes (for my current implementation I am only interested in the case where the user checks "Location"+ "Pipe-Type" + "Amount") in my action page "fe_page2.php", the if condition that checks to see if the checkboxes are checked is never being reached instead it always goes to the else condition. The code is provided below.
This is my basic html page:
<html>
<head>
<title>Flow Element</title>
</head>
<body>
<h1 style="margin-left: 450px">Retrieve Flow Element Information</h1>
<hr>
<form action="fe_page2.php" method="post">
All Times:
<input type="checkbox" name="alltimes" onchange="changeFields()"><br><br>
Start Date:
<input type="date" name="startdate" id="startdate">
Start Time:
<input type="time" name="starttime" id="starttime"><br><br>
Same Time:
<input type="checkbox" name="sametime" id = "sametime" onchange="sameFields()"><br><br>
End Date:
<input type="date" name="enddate" id="enddate">
End Time:
<input type="time" name="endtime" id="endtime"><br><br>
<h3> Select fields of output</h3>
<hr>
Pipe Key: <input type="text" name="pipepirmary" id="pipekey"><br>
<input type="checkbox" name="pipelocation" id="pipeLocation" value="value1" >
Location<br>
<input type="checkbox" name="Pipe-Type" id="pipetype" value="value2">
Pipe-Type<br>
<input type="checkbox" name="amount" id="amount" value="value3">
Amount<br><br>
Flow Element:<input type="text" name="fepirmarykey" id="fekey"/><br>
<input type="checkbox" name="flow" id="flo">
Flow<br>
<input type="checkbox" name="temperature" id="temp">
Temperature<br>
<input type="checkbox" name="pressure" id="pres">
Pressure<br><br>
<input type="submit">
</form>
<script>
function changeFields() {
if(document.getElementById("startdate").disabled == false){
document.getElementById("startdate").disabled = true;
document.getElementById("starttime").disabled = true;
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("sametime").disabled = true;
if(document.getElementById("sametime").checked = true){
document.getElementById("sametime").checked = false;
}
document.getElementById("startdate").value = null;
document.getElementById("starttime").value = null;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("startdate").disabled = false;
document.getElementById("starttime").disabled = false;
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
document.getElementById("sametime").disabled = false;
}
}
function sameFields() {
if(document.getElementById("enddate").disabled == false){
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
}
}
</script>
</body>
</html>
This is the php page fe_page2.php
<?php
require('dbconf.inc');
db_connect();
print"<pre>";
print_r($_POST);
print"</pre>";
$pipelocation = $_POST[pipelocation];
$pipetype = $_POST[Pipe-Type];
$pipeamount = $_POST[amount];
if($pipelocation=='value1' && $pipetype == 'value2' && $pipeamount == 'value3'){
$qrySel="SELECT `Pipe_ID`, `Location`, `Amount`, `PipeType` FROM pipe order by Pipe_ID desc";
$resSel = mysql_query($qrySel);
if($resSel){
while($rowpipe = mysql_fetch_array($resSel, MYSQL_ASSOC)){
echo "Pipe ID:{$rowpipe['Pipe_ID']} <br> ".
"Location: {$rowpipe['Location']} <br> ".
"Amount: {$rowpipe['Amount']} <br>".
"PipeType: {$rowpipe['PipeType']} <br>".
"--------------------------------<br>";
}
echo "Fetched Data Successfully!\n";
}
}
else{
echo"never went in!";
}
db_close();
?>
I have tried different things such as
if(isset($pipelocation) && isset($pipetype) && isset($pipeamount)){
.....
}
and removing the value from html page and using the following piece of code:
if($pipelocation == 'on' && $pipetype == 'on' && $pipeamount == 'on'){
...
}
But still no luck...
Any help would be appreciated.
The code that is presented is purely my work but does include pieces of code that comes from the provided reference below:
https://www.youtube.com/watch?v=LZtXYa9eGGw

You missed the quotations here:
$pipelocation = $_POST['pipelocation'];
$pipetype = $_POST['Pipe-Type'];
$pipeamount = $_POST['amount'];

Related

PHP/HTML submit redirection to 404 not found

I'm creating a simple web app that calculates the age of when you're going to graduate. My program runs fine in eclipse but as soon as I push it to the server and push my button (submit) it redirects to a 404 error. I'm using ipages and I'm aware that they are using php 5.6. Any helpful tips would help out a ton.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<title>Graduation Calculator</title>
</head>
<body>
<img alt="Image goes here..." src="Balloon-Banner.jpg" width = "1050" height="180">
<form action="grad.php" method="POST">
<center>
<br>
<br>
<br>
<label><?php echo "Today is " . date("m/d/Y"); ?></label>
<br>
<br>
<br>
<label>Enter your birth year: </label>
<input type="text" name="birthYear" />
<label>Enter your graduation year: </label>
<input type="text" name="gradYear" />
<br>
<label>Enter your Birth Month: </label>
<input type = "text" name = "birthMonth"/>
<label> Enter your graduation month</label>
<input type = "text" name = "gradmonth" />
<br>
<label> Enter your birthday</label>
<input type = "text" name = "birthDay" />
<label>Enter your graduation day: </label>
<input type="text" name="gradday" />
<br>
<input type='submit' value='Graduation Age' id = 'submit' />
</center>
</form>
<?php
$submitted = ! empty ( $_POST );
if ($submitted == true)
{
$bYear = (int) $_POST ['birthYear'];
$gYear = (int) $_POST ['gradYear'];
$gMonth = (int) $_POST['gradmonth'];
$bMonth = (int) $_POST['birthMonth'];
$bday = (int) $_POST['birthDay'];
$gday = (int) $_POST ['gradday'];
$age = getAge($bYear, $gYear, $bMonth, $gMonth, $bday, $gday);
if($age!= NULL){
echo "You will be " . $age . " at your graduation.";
}
else{
echo "INVALID INPUT, PLEASE TRY AGAIN";
}
}
function getAge( $bYear, $gYear, $bMonth, $gMonth, $bday, $gday)
{
If($bYear> $gYear || $bMonth>12 || $gMonth >12 || $bday >31 || $gday >31 || $bYear == 0 || $gYear == 0 || $bMonth == 0 || $bday == 0 || $gMonth ==0|| $gday == 0){
return NULL;
}
$age = $gYear - $bYear;
if($bMonth == $gMonth){
if($bday <= $gday){
return $age;
}
else{
$age = $age-1;
return $age;
}
}
elseif($bMonth < $gMonth){
return $age;
}
else{
return $age-1;
}
return $age;
}
?>
</body>
</html>
If you're executing your front-end and back-end code in the same file, just keep it simple and just do it in the same file unless you have a framework.
Change <form action="grad.php" method="POST"> to <form method="POST">.
Should work, if not we'll try to work something out ;)
Remove the action="grad.php" from form. So it will submit to self.

PHP session array and input validation

Currently I am sending error messages and storing the value of my input fields in sessions.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductPrice']; unset($_SESSION['msgProductPrice']); ?></label>
<input type="text" name="product_price" value="<?php echo $_SESSION['val_ProductPrice']; unset($_SESSION['val_ProductPrice']); ?>" />
PHP
$Price = $_POST['product_price'];
$errorcount = 0;
if(empty($Price) === true){
$PriceErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductPrice'] = $Price;
$_SESSION['msgProductPrice'] = $PriceErrormsg;
}
This works perfectly with one of a kind input field. If I try with multiple input fields with the same name, it doesn't work.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
This is where I'm unsure on how to validate all the input fields, how to keep the value in each input field when you hit submit and how to send an errormsg about each field?
PHP
$Amount= $_POST['product_amount'];
$errorcount = 0;
if(empty($Amount) === true){
$AmountErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrormsg;
}
If I understand your problem, multiple product amounts are being submitted, and you want to validate each one individually and display the error message next to the appropriate textbox?
Because you are receiving an array of values, you need to create a corresponding array of error messages.
It's a while since I've done any PHP, so this might not be 100% correct, but I think you need something along these lines...
$AmountErrorMessage = Array();
foreach ($Amount as $key => $value) {
if (empty($value)) {
$AmountErrorMessage[$key] = 'empty';
}
}
if ($AmountErrorMessage->count() > 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrorMessage;
}
You would then also need to iterate through the array in order to generate the HTML for your form, creating a label and input box for each value submitted.
This code help you to do it as per your wish..
<?php
session_start();
?>
<html>
<head>
<title></title>
<style>
.errormsg{
color:red;
}
</style>
</head>
<body>
<?php
if(isset($_POST['product_amount']))
{
$errorcount = 0;
for($i=0;$i<count($_POST['product_amount']);$i++){
$Amount[$i] = $_POST['product_amount'][$i];
if(empty($Amount[$i]) === true){
$_SESSION['msgProductAmount'][$i] = "empty";
$errorcount++;
}
else
$_SESSION['val_ProductAmount'][$i] = $Amount[$i];
}
if($errorcount === 0) {
unset($_SESSION['msgProductAmount']);
echo "success";
}
}
?>
<form action="" method="POST">
<?php
$cnt = 10;
for($i=0;$i<$cnt;$i++){
?>
<input type="text" name="product_amount[<?=$i?>]" value="<?php echo isset($_SESSION['val_ProductAmount'][$i]) ? $_SESSION['val_ProductAmount'][$i] : '';?>" />
<label class="errormsg"><?php echo $res = isset($_SESSION['msgProductAmount'][$i]) ? $_SESSION['msgProductAmount'][$i] : '' ; ?></label>
<br/>
<?php
}
?>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
unset($_SESSION['msgProductAmount'],$_SESSION['val_ProductAmount']);
?>

PHP questionnaire strategy

I am designing a questionnaire, the code I've written is a combination of JS and PHP. I have the questions in one page but I want to ask each question on a separate page and the consecutive questions should be asked according to the answer the user select. what is the best strategy to do that? do I need to include SQL as well?
and at the end the answers will be written in a text file
the code I have is:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['name']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
$varName = $_POST['name'];
$varLand1 = $_POST['landscape1']; $varLand2 = $_POST['landscape2'];
$varCom = $_POST['comment'];
$varAppx = $_POST['appx'];
$clim = $_POST['landscape'];
$varMech = $_POST['mechanism'];
$varMechoth = $_POST['mech'];
if(empty($errorMessage))
{
$fs = fopen("$varName.txt" ,"a+");
fwrite($fs,$varName . "\n" . $varLand1 . ' ' .$varLand2 . "\n" . $clim . "\n" . $varAppx . "\n" . $varCom . "\n" . $varMech .$varMechoth);
fclose($fs);
header("Location: t-y.html");
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script scr="jss.js" type="text/javascript"></script>
<title>Questionnaire</title>
</head>
<body>
<FONT FACE="Times New RomanPS">
<H1>Questionnaire</H1>
<P>Please fill out this questionnaire:
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="index.php" method="post">
<p>
Name<br>
<input type="text" name="name" maxlength="50" value="<?=$varName;?>" />
</p>
<ul>
<p> 1 - Q1?
<p><input type="checkbox" name="landscape1" value="urban"> Urban<br>
<p><input type="checkbox" name="landscape2" value="non-urban"> non-Urban<br>
<p> 2 - Q2?<br>
<input type="radio" name="landscape" value="Dry"> Dry<br>
<input type="radio" name="landscape" value="Tropical"> Tropical<br>
<input type="radio" name="landscape" value="Moderate"> Moderate<br>
<input type="radio" name="landscape" value="Continental"> Continental<br>
<input type="radio" name="landscape" value="Polar"> Polar<br>
<p> 3 - Q3? <br>
<input type="radio" id="mecha" name="mechanism" value="sub" onclick="hideTextBox1()"/> Subsidence<br>
<input type="radio" id="mecha" name="mechanism" value="earth" onclick="hideTextBox1()"/> Earthquake<br>
<input type="radio" id="mecha" name="mechanism" value="volc" onclick="hideTextBox1()"/> Volcanic<br>
<input type="radio" id="mecha" name="mechanism" value="<?=$varMech;?>" onclick="displayTextBox1()"/> other<br>
<div id="otherTextBox1" style="display:none;visibility:hidden;">
<input type="text" name="mech" maxlength="20" value="<?=$varMech;?>">
</div>
<p> 4 - Q3?<br>
<input name="choice" id="choice4" type="radio" value="four" onclick="hideTextBox()"/><label for="choice4"> No </label><br>
<input name="choice" id="choice5" type="radio" value="other" onclick="displayTextBox()"/><label for="choice5"> Yes </label>
<br/>
<div id="otherTextBox" style="display:none;visibility:hidden;">
[mm/yr]<br><input type="text" name="appx" maxlength="3" value="<?=$varAppx;?>">
</div>
<br/>
<p> 5 - Q4
<p> 6 - Q5
<p> 7 - Q6
<p>
Comments:<br>
<textarea type="text" name="comment" cols=48 rows=4 maxlength="1000" value=" <?=$varComment;?>"></textarea>
</p>
<p><input type="reset"> <input type="submit" name="formSubmit" value="Submit" />
</ul>
<script>
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
function displayTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'block';
otherTextBox1.style.visibility = 'visible';
}
function hideTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'none';
otherTextBox1.style.visibility = 'hidden';
}
function validate1()
{
var arrElements1 = document.getElementsByName('mechanism');
var objElement1;
var boolContinue = false;
var objotherText1;
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else<?=$varMech;?>
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
</script>
</form>
</FONT>
</body>
</html>
I don't think you would NEED to use SQL to do this. You should be able to use the $_SESSION to store the answers to previous questions and adjust the questions on the following pages accordingly.

Not able to submit multiple forms on single html page

I have problem with forms on one file.
The problem is that when I click submit ... it submits the first form data instead of the form that the person filled even though as you can see from the code below that I specified a certain id for each form.
I am using a php file to submit the data to mysql
here is my code:
case 'upd_chpt':
if($_POST['does'] == 'upd_chpt')
{
$chId = $_POST['chId'];
$name = $_POST['name'];
$nums = $_POST['nums'];
$mngs = $_POST['mang'];
$ch_trans = $_POST['ch_trans'];
$ch_down = $_POST['ch_down'];
$ch_translate = $_POST['ch_translate'];
$ch_clean = $_POST['ch_clean'];
$ch_editor = $_POST['ch_editor'];
if(!empty($chId) && !empty($name) && !empty($nums) && !empty($mngs) && !empty($ch_trans))
{
$mnG = explode(',' , $mngs);
$qup = $db->query("UPDATE chapter SET ch_name = '".$name."', chapter_num = '".$nums."', manga_id = '".$mnG[0]."', manga_title = '".$mnG[1]."', manga_name = '".$mnG[2]."', ch_down = '".$ch_down."', ch_translate = '".$ch_translate."', ch_clean = '".$ch_clean."', ch_editor = '".$ch_editor."', ch_trans = '".$ch_trans."' WHERE ch_Id = '".$chId."' ");
if($qup)
{
echo "updated successfully";
}
else
{
echo "erorr ";
}
}
else
{
echo "please fill all the fields !";
}
}
break;
html code :
<form id="edit_{$ch[ch].ch_Id}">
<input type="hidden" name="chid" value="{$mn[mn].ch_Id}" />
<label>chapter number</label>
<input type="text" id="chaptr" name="chaptr" value="{$ch[ch].chapter_num}" class="short" />
<label>chapter title </label>
<input type="text" id="name" name="name" value="{$ch[ch].ch_name}" class="short" />
<label>manga related to chapter</label>
<select id="mansga" name="manga">
{section name='mn' loop=$mng}
<option value='{$mng[mn].mn_Id},{$mng[mn].mn_title},{$mng[mn].mn_name}' {if $mng[mn].mn_Id==$ch[ch].manga_id}selected="true" {/if}>
{$mng[mn].mn_name}
</option>
{/section}
</select>
<label>chapter link</label>
<input type="text" id="ch_down" name="ch_down" value="{$ch[ch].ch_down}" class="short" />
<label>all credit goes to</label>
<input type="text" id="ch_trans" name="ch_trans" value="{$ch[ch].ch_trans}" class="short" />
<label>translated by</label>
<input type="text" id="ch_translate" name="ch_translate" value="{$ch[ch].ch_translate}" class="short" />
<label>cleaned by</label>
<input type="text" id="ch_clean" name="ch_clean" value="{$ch[ch].ch_clean}" class="short" />
<label>edited by</label>
<input type="text" id="ch_editor" name="ch_editor" value="{$ch[ch].ch_editor}" class="short" />
<label><input type="submit" class="submit" value="تعديل" /></label>
</form>
javascript :
$('[id^=edit_]').submit(function(){
var id = $(this).attr('id').split('_')[1];
var name = $('#name').val();
var nums = $('#chaptr').val();
var mang = $('#mansga').val();
var ch_trans = $('#ch_trans').val();
var ch_down = $('#ch_down').val();
var ch_translate = $('#ch_translate').val();
var ch_clean = $('#ch_clean').val();
var ch_editor = $('#ch_editor').val();
$.post("action.php", {does: 'upd_chpt' ,ch_trans:ch_trans, ch_down:ch_down, ch_translate:ch_translate , ch_clean:ch_clean , ch_editor:ch_editor , chId:id , name: name, nums: nums, mang:mang},function(m){
alert(m);
});
return false
});
can this code be changed ? and be only php + html without javascript ! ... because I think that id="" is the problem
the mistake was on the second line
{$mn[mn].ch_Id} should be {$ch[ch].ch_Id}

Help PHP and HTML Checkboxes

I need help working with Checkboxes and PHP. I'm just trying to determine a value on whether the checkbox is checked or not with PHP.
Example:
<?php
include ("inc/conf.php");
$id = $_SESSION['id'];
if(isset($_POST['subfrm'])){
$gtid = $_REQUEST['tid'];
$ch1 = $_REQUEST['ch1'];
if($ch1 == "ON"){
$gch1 = "Y";
} else {
$gch1 = "N";
}
$ch2 = $_REQUEST['ch2'];
if($ch2 == "ON"){
$gch2 = "Y";
} else {
$gch2 = "N";
}
mysql_query("UPDATE SET ctable ch1='$gch1', ch2='$gch2' WHERE id='$gtid'");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="tid" value="<?php echo $id; ?>" />
<input type="checkbox" name="ch1" />Hats
<input type="checkbox" name="ch2" />Watches
<textarea name="thetext"></textarea>
<input type="submit" name="subfrm" value="PUNCH ME" />
</form>
if(isset($_REQUEST["ch1"])){
$gch1 = "Y";
} else {
$gch1 = "N";
}
if(isset($_REQUEST["ch2"])){
$gch2 = "Y";
} else {
$gch2 = "N";
}
You don't need to check to see what the value is, because it will not submit any data whatsoever if it isn't checked, and it will submit a value of on if it is.
Try this:
<?php
$ch1 = isset($_REQUEST['ch1']);
If the check box wasn't checked, its corresponding variable won't show up in the request.
Through this together. It will let you know which checkbox was selected and it will also retain the check on form submit.
<?php
$message = '';
$ch1_checked = false;
$ch2_checked = false;
if(isset($_POST['submit_button'])) {
// Form was submitted
$ch1_checked = isset($_POST['ch1']);
$ch2_checked = isset($_POST['ch2']);
if($ch1_checked && $ch2_checked) {
$message .= 'Both were checked.';
} else if($ch1_checked) {
$message .= 'Checkbox 1 was checked.';
} else if($ch2_checked) {
$message .= 'Checkbox 2 was checked.';
} else {
$message .= 'Neither were checked.';
}
}
?>
<?php echo $message; ?>
<form id="my_form" action="test.php" method="post">
<input type="checkbox" name="ch1" value="ch1" <?php if($ch1_checked) echo 'checked'; ?> />Checkbox 1<br />
<input type="checkbox" name="ch2" value="ch2" <?php if($ch2_checked) echo 'checked'; ?> />Checkbox 2<br />
<input type="submit" name="submit_button" value="Go!" />
</form>

Categories