Seems like the last stretch is getting harder!
So I have if statements and inside those statements code should execute if they are true. The problem is the code is executing even though its no true.
Code that execute even though Spproved is set to 1
if($user_data['permissions'] >= 1)
{
// If users permission is 1 or 2 they get a field for inputting the index # and a button to change the approve field from 0 to 1 may need to make a new field to record who approved it....
//Determine if the order is already approved. If not approved show index field and allow user to approve it with index number
if($data2[0]['Approved'] == 1)
{
echo " <font color=\"green\"> Approved";
}
else if($data2[0]['Approved'] == 0)
{
echo " Not Approved. Supply an index number and click approve to authorize this order to be completed.";
if (empty ($_GET) === false)
{
$required_fields = array('IndexNum');
foreach ($_GET as $key=>$value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (isset($_GET['success']) === true && empty($_GET['success']) === true)
{
echo 'Index has been updated and Order is now set to Approved';
}
else
{
if (empty($errors) === true)
{
$indexnum=$_GET['IndexNum'];
$approvedby=$user_data['lname'];
$vendorid1= $_GET['hidden1'];
update_approved($approvedby, $indexnum, $vendorid1);
header('Location: index.php');
exit();
}
else if(empty($errors) === false)
{
echo output_errors($errors);
}
}
}
?>
<form name="approveform" method="GET" action="">
<input type="hidden" name="hidden1" value="<?php echo $id;?>">"
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
<?php }
}
if($user_data['permissions'] == 2)
{
// If user is permission 2 they can have a button to say shipped... Do I need to record who shipped it? for now nah. Would be nice to input a data of arrival though. I will think on it .... pretty lazy
if($data2[0]['Approved'] == 1)
{
echo "<br/>";
echo "Confirm order has been ordered";
if(isset($_GET['Ordered']))
{
$vendorid1=$_GET['hidden1'];
echo $vendorid1;
//update_shipped($vendorid1);
//header('Location: index.php');
//exit();
}
?>
<form name="approveform" method="GET" action="">
<input type="hidden" name="hidden1" value="<?php echo $id;?>">
<input type="submit" name="Ordered" value="Ordered" action="">
</form>
<?php
}
}
IT shows Approved in green on the form and the Ordered button comes up fine. When I click the submit button the code in the else if($data[0]['Approved'] == 0) activates instead of the code the isset. Approved is set to 1 So I have no idea why that code is running.....
Value of print_r($data2) is
Array ( [0] => Array ( [VendorName] => Newegg [DateRequested] => 2013-09-25
[DateNeeded] => 0000-00-00 [Shipping] => Standard [VendorNumber] => 123123
[VendorFax] => NA [VendorAddress] => 1 ave new [VendorCity] => socorro
[VendorState] => nm [VendorZip] => 87114 [EquipmentConsumable] => Consumable
[GasType] => propane [GasLocation] => United States [UNMTag] => 0
[EquipmentLocation] => [index] => 414141 [totalcost] => 129.88
[Approved] => 1 [Shipped] => 0 ) )
Use strict comparisons, === and !== instead of == and !=. PHP tends to evaluate 1 and 0 as boolean unless told explicitly otherwise.
Also, with functions like empty(), you can change:
if( empty($_GET) === FALSE ) to if( !empty( $_GET ) )
if( empty($_GET) === TRUE ) to if( empty( $_GET ) )
As they return boolean.
Since you are using $_GET, make sure all the variables you need per pass are in the url. Since the form elements can only pass the nested input elements, you may require more hidden information to pass after submit. Also, you should probably put the file name in action="" or omit it from the form tag.
I know this is not going to solve your problem but....
You have an extra "
right here
|
V
<input type="hidden" name="hidden1" value="<?php echo $id;?>">"
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
Related
Could you please inform how to check one of the form input fields is not empty in php, no matter what input field names are.
<form name="form1" method="POST">
<input type="text" name="a">
<input type="text" name="b">
</form>
However, please do not inform me the following codes as I know.
if ($_POST["a"] != "" || $_POST["b"] != "")
{ [proceed....] }
Loop through the POST array and test the value like this perhaps
if( $_SERVER['REQUEST_METHOD']=='POST' ){
foreach( $_POST as $field => $value ){
if( !empty($value) ){
exit( $field . 'is NOT empty' );
}
}
}
The if statement can get quite long if there are multiple input fields.
You should use array_filter() function on POST data.
Try this:
if (array_filter($_POST)) {
echo "Proceed";
} else {
echo "One of the fields is blank";
}
I'm trying to create a code logic by using a for loop instead of multiple if statements.
This is the previous if statement code I used before:
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct[0];
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect[0];
}
};
This code allows me to check for the answer and print either the $correct or $incorrect variable. My issue in this code is that it is very inefficient because I end up having to create ten or so if statements.
I came up with a mock-up of the for loop code to illustrate:
$_SESSION["totalCorrect"] = 0;
if (!isset($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
$postAns = array($_POST['answer1'] as $ans1, $_POST['answer2'] as $ans2, $_POST['answer3'] as $ans3, $_POST['answer4'] as $ans4, $_POST['answer5'] as $ans5, $_POST['answer6'] as $ans6,
$_POST['answer7'] as $ans7, $_POST['answer8'] as $ans8, $_POST['answer9'] as $ans9, $_POST['answer10'] as $ans10);
for ($i = 0; $i < count($postAns); i++)
{
if ($i == $postAns[])
{
if ($postAns[] === 'answer')
{
print $correct[];
$_SESSION["totalCorrect"]++;
}
else ()
{
print $incorrect[];
}
}
};
For this code, I have three arrays involved that I am trying to cycle through, $postAns, $correct, and $incorrect. The $correct and $incorrect arrays, when called, print out text depending on whether they got the answer right.
So for the for loop, I want to be able to cycle through each value of the $postAns array to check and and see which answer number it is and whether it is the correct answer or not. If it's correct, then the code cycles through $correct to get the right text for that answer number and increments the value of totalCorrect, the variable that stores how many the user got right. If incorrect, the code cycles through $incorrect to get the right text for that answer number.
I'm not really proficient with loops in general so any insight/help would be greatly appreciated.
EDIT: Included the form submission code
<form action="staff_info.php" method="get" id="q1">
<fieldset>
<legend>Question 1</legend>
<input type="radio" name="answer1" value="1a" id="1a"><label for="1a"> A. </label>
<input type="radio" name="answer1" value="1b" id="1b"><label for="1b"> B. </label>
<input type="radio" name="answer1" value="1c" id="1c"><label for="1c"> C. </label>
<input type="radio" name="answer1" value="1d" id="1d"><label for="1d"> D. </label>
<input type="button" id="answer" class="button " title="abutton" value="ANSWER">
NEXT
</fieldset>
The one thing you're missing in your pseudo code is the actual answers. If you create an array of correct answers as #fefe indicated then the loop will be something like this:
$correctAnswers = array(
'answer1'=>'1d',
'answer2' => '2b',
'answer3' => '3c',
'answer4' => '4b',
'answer5' => '5a'
);
$numberCorrect = 0;
$responseIndex = 0;
foreach ($correctAnswers as $key=>$answer) {
if ($_POST[$key] === $answer) {
$numberCorrect++;
print $correct[$responseIndex];
}
else {
print $incorrect[$responseIndex];
}
$responseIndex++;
}
I don't really know what you trying to achieve but the loop should look something like this and you can make some validation with if or switch case.
$postAns = array(
'answer1'=>'ans1',
'answer2' => 'ans2',
'answer3' => 'ans3',
'answer4' => 'ans4',
'answer5' => 'ans5',
'answer6' => 'ans6',
'answer7' => 'ans7',
'answer8' => 'ans8',
'answer9' => 'ans9',
'answer10' => 'ans9'
);
foreach ($postAns as $key=>$ans) {
var_dump($ans);
}
In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!
<form action="http:\\127.0.0.1\rechecking.php" method="post" enctype="multipart/form- data"><pre>
Enter your first Name: <input type="text" name="fname" size="15"></input>
Enter your Last Name: <input type="text" name="lname" size="15"></input>
Your Email Id: <input type="text" name="email" size="15"></input>
Your age: <input type="text" name="age" size="1"></input>
Upload your Image: <input type="file" name="file"></input>
<input type="Submit" value="Submit"></input></pre>
</form>
<?php
if(!empty($_POST["fname"])&&!empty($_POST["lname"])&&!empty($_POST["email"])&&!empty($_POST["age"]))
{
if($_FILES["file"]["error"]>0)
{
echo $_FILES['file']['error'] ."error is there in uploading files";
}
}
else
{ $emt=array($_POST['fname']=>"Firstname",$_POST['lname']=>"LastName",$_POST['email']=>"Email",$_POST['age']=>"Age");
foreach($emt as $value=>$variable)
{
if(empty($value))
{
echo $variable." cannot be left blank<br />";
}
}
}
?>
The problem is that on leaving all the spaces blank in my formIts only showing the last ement of associative array.
For ex:-Leave firstname,lastname ,email, age then it will just show 'Age filed cannot be left blank'
Similarly if age is already filled in my input field then it will just show 'Email field can not be left empty'
Well I want it to display names of all fields that are left empty
You have to change $key and $variable:
$emt=array("Firstname"=>$_POST['fname'],"LastName"=>$_POST['lname'],"Email"=>$_POST['email'],"Age"=>$_POST['age']);
Change it as
$emt=array("Firstname"=>$_POST['fname'],"LastName"=>$_POST['lname'],"Email"=>$_POST['email'],"Age"=>$_POST['age']);
I think you're confusing:
foreach($emt as $value=>$variable)
{
with
foreach($emt as $variable=>$value)
(I would name the variable $variable $key instead, but's just a matter of taste)
And the same thing goes for the array which other answers has shown.
$emt = array(key => value, key => value, ....);
In order to check if a specific key is empty, you must make sure that it's set first (user can edit his HTML source and not send some field, triggering some warnings in your site).
Other than that, I find your code a little messy so you will find it difficult to debug or read after a while.
Here, I'm rewriting the PHP part to check the field is entered and is not empty.
<?php
$required = array(
'fname' => 'First name',
'lname' => 'Last name',
'email' => 'Email address',
'age' => 'Age',
);
$errors = array(); // Here, we store all the error messages. If it's empty, we are good to go.
foreach ($required as $key => $label) {
if (isset($_POST[$key]) || empty($_POST[$key])) {
$errors[] = "$label field is required.";
}
}
if (!isset($_FILES["file"])) {
$errors[] = 'Please upload an image';
}
elseif (isset($_FILES['file']['error']) && $_FILES['file']['error']) {
$errors[] = 'An error occurd while uploading your photo';
}
if ($errors) {
print '<ul>';
foreach ($errors as $error) {
print "<li>$error</li>";
}
print '</ul>'
}
else {
// All fields are filled and not empty, file is uploaded successfully. Process your form.
}
?>