If-else statement if theres no value input - php

Im trying to handle error in my code, how do i if-else when there is no value on the input of user and the user calculates it?
<h1> Triangle</h1>
<div style="border:1px solid black">
<form action="triangle.php" method="get">
Base: <input type="number" name="base"> meters
<br>
Height: <input type="number" name="height"> meters
<br>
<input type="submit" value="Calculate">
</form>
</div>
<?php
if (isset($_GET['base'])) {
$base1 = $_GET['base'];
$height1 = $_GET['height'];
$area = triangleArea($base1, $height1);
echo "Area is: " . $area;
}
?>

You're already checking whether the base value exists or not. It looks like you need to also check whether the height value exists - so just add that into the isset function call:
if (isset($_GET['base'], $_GET['height'])) {

Related

How to input another value with looping statement in PHP?

Hello I am new to programming and I am having a hard time with this. Can someone please give me a tip or help with my code?
The user will be asked if they want to input another value and if they click the "yes button", a text field will show wherein the user will input another value. Or the button can redirect them to the process page again to input another value, something like that. It must be done using looping statement. I tried do while loop but it doesn't seem to work or maybe I am doing wrong. Any help or tip is appreciated.
This is my code on button:
<?php
if(isset($_POST['f-value'])):
$total=($_POST['f-value']-32)*5/9;
echo round($total, 3) . " celcius";
endif;
?>
<?php
if(isset($_POST['base'])):
$areat = 1/2 * $_POST['base'] * $_POST['height'];
echo "The Area of a Triangle is ";
echo round($areat, 3);
endif;
?>
<?php
if(isset($_POST['length'])):
$perimeter=($_POST['length']+$_POST['width'])*2;
echo "The Perimeter of the Rectangle is ";
echo round ($perimeter,4);
endif;
?>
<?php
if(isset($_POST['radius'])):
$Pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067;
$diameter= ($_POST['radius'] * 2);
$areac= $Pi * $_POST['radius'] * $_POST['radius'];
$circum= 2 * $Pi * $_POST['radius'];
echo "The Area of the Circle is ";
echo $_POST['radius'];
echo round($areac,3);
echo "<br>The Circumference of the Circle is ";
echo round($circum,3);
echo "<br>The Diameter of the Circle is ";
echo round($diameter,3);
endif;
?>
<form action="process.php" method="post">
Input again?: <input type="submit" value="Yes" name="yes">
<input type="submit" value="No" name="no">
</form>
This is my code on PHP process file:
<?php
function formFunction(){
if(isset($_POST['formula'])):
$selection=$_POST['formula'];
switch($selection):
case 'default':
echo "Please select a formula";
break;
case '1':?>
<form action="output.php" method="post">
Radius: <input type="text" name="radius">
<input type="submit" value="Compute">
</form>
<?php
break;
case '2':?>
<form action="output.php" method="post">
Fahrenheit: <input type="text" name="f-value">
<input type="submit" value="Compute">
</form>
<?php
break;
case '3':?>
<form action="output.php" method="post">
Base: <input type="text" name="base">
Height: <input type="text" name="height">
<input type="submit" value="Compute">
</form>
<?php break;
case '4':?>
<form action="output.php" method="post">
Length: <input type="text" name="length">
Width: <input type="text" name="width">
<input type="submit" value="Compute">
</form>
<?php break;
endswitch;
endif;}?>
<?php
//I tried looping here but doesn't seem to work fine. It works but it displays infinite loop or it doesn't display at all
?>
add these blocks of code in process.php
if(isset($_POST['yes'])) :
header("Location: https://file_path.php");
die();
endif;
if(isset($_POST['no'])):
echo "Thank You!";
endif;
here, in header write your file path where you want to redirect like if you are using localhost than header("Location: localhost/folder_name/file_name.php");
if still you have queries comment down i will help you out till i can

PHP: why variable does not get reloaded after a Submit?

Here is a code that I've made:
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
When I enter some text in the form and click Validate, the page display sum=1, but after this, when I enter nothing in the form and click Validate, the page STILL displays sum=1.
Why does the variable $sum is not reloaded between the two Validate ? Is there a way to escape it ?
Thanks
This will solve the issue
<?php
$sum=0;
if(isset($_POST['name']) && $_POST['name'] != ''){
$sum+=1;
}
echo "sum = $sum";
?>
This is because isset() checks for the existence of the $_POST variable. In your case, the $_POST variable exists and has an empty string value.
Your code will work if you change isset() to !empty() like so;
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(!empty($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
More about the empty() function here.
Another way would be to check the request that your client has made on your page. So that if it is a simple refresh (not with a form refresh), it is a GET request and so, the variable should not be incremented and if the form has been sent, then you can do whatever you want such as incrementing the data.
So if the client is sending the form with an input text filled, then you can increment the value. In all other cases, the value should remain a zero.
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && !empty($_POST['name']))
{
$sum++; /* strictly equivalent to: $sum += 1; */
}
?>
<samp>sum = <?php echo $sum; ?></samp>
Try this
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['submit'])){
$sum+=1;
}
echo "sum = $sum";
?>
You can try below:
if(isset($_POST['name']) && strlen($_POST['name'])>0){
$sum+=1;
You have the code appending 1 to variable $sum
but your if statement is based on the name field being passed.
Not if the name field has any data in it.
So... you have made your code add 1 as long as name field is passed,
regardless if it has text input or not.
Also, you should reassign the varible to reset it.
+= should just be =
<form method="post" action="test.php">
//----------------------------- add empty value to input ------------
<input type="text" name="name" value="" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum=1;
}
echo "sum = $sum";
?>

How to compare form data in php

HTML/PHP:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" name="imageval" />
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
PHP:
$arrImg = array("img1", "img2", "img3", "img4", "img5", "img6");
$arrImgText = array("56", "342", "34534", "12", "444", "652");
$imgval = trim(strip_tags(stripslashes($_POST['imageval']))); //get the image source that was displayed in the form
$numval = trim(strip_tags(stripslashes($_POST['numval']))); //get the number that the user entered
//if ({arrImg[imgval] == arrImgText[numval]}) {
//do something;
//}
The image that is displayed in the form has some numbers. When the user hit send, I would like to compare the number that was entered that was displayed in the image and compare.
How can I do that.
In your form, create hidden input:
<input type="hidden" name="imageval" value="img1" />
In your PHP file you can have now two $_POST variables:
$secretImg = $_POST['imageval'];
$token = $_POST['numval'];
Now you need to find key of image:
$imgKey = array_search($secretImg, $arrImg);
Using the key value, check the proper token:
if ($arrImgText[$imgKey] === $token) {
// Token is valid
}
You can't pass images because it is not an input element, what you could do is use a hidden input element instead:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" />
<input type="hidden" val="img1" name="imageval" /> <!-- THIS IS THE HIDDEN INPUT ELEMENT THAT WILL BE SUBMITTED -->
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
In order to search the image value in the array using PHP, you can use in_array:
if( in_array( $_POST['imageval'], $arrImgText ) {
echo "Image found";
}
Edit: To get the specific index, use the example in #GrzegorzGajda'a answer

PHP getting selected table rows from checkboxes

I have a PHP form where a table is created of all files in a folder on the server, and each row created is assigned a checkbox which will be used to decide which files are to be deleted or shared etc. Each row is given a name checkbox[$rownumber] to distinguish each, and then when a button is clicked, for the moment to ensure I can get it working, it just prints the rows that are selected - but I can't get this working.
Initially, as rows are created in the table from the server, this is the code, which correctly creates them as I wish
<?php
if(isset($_REQUEST['deleteFile']))
{var_dump($_REQUEST);
if(isset($_POST['checkbox']))
{
print_r($_POST);
}
}
?>
<form name="mainHomescreen" action="MainHomescreen.php" method="POST">
<nav>
<input type="text" name="Search" value="Search" style = "color:#888;" onFocus="inputFocus(this)" onBlur="inputBlur(this)"/>
</nav>
<sidebar>
<input type="button" value="Create Folder" onClick="createFolder()"/>
<input type="button" value="Download Selected Files/Folders" onClick=" "/>
<input type="button" value="Encrypt Selected" onClick="encrypt()"/><br>
<input type="button" value="Share Selected" onClick="shareFolder()"/>
<!-- upload a file -->
<div id="fileUpload">
<div id="uploadPopup">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="uploadForm" method="post" name="uploadForm" enctype="multipart/form-data">
Select file to upload: <input name="fileUpload" type="file" /><br />
<input type="submit" value="Upload File" name="submitFile"/>
</form>
</div>
</div>
<input type="button" name="upload" value="Upload File" onClick="showUpload()"/>
<input type="submit" value="Delete" name="deleteFile"/>
<input type="button" value="Rename" onClick=" "/><br>
<input type="button" value="Password Protect Folder/ File" onClick=" "/><br><br>
</sidebar>
<article>
<span class="error"><?php echo $error;?></span>
<table id="detailView" style="width:100%">
<!-- php to create table -->
<?php
//open file names
$dir = opendir("/home/a1962403/public_html/files");
$filearray = array(array(array()));
echo '<table cellpadding="10" cellspacing="0" style="width:100%">';
echo '
<tr>
<th> </th>
<th>File</th>
<th>Date</th>
<th>Size</th>
</tr>
';
$rownumber = 0;
//List files in directory
while (($file = readdir($dir)) !== false)
{
//gets the file date, string needed decoding otherwise throws error.
$date = #filemtime($file);
$date = date("F d Y H:i:s.", filemtime(utf8_decode("/home/a1962403/public_html/files/$file")));
$size = filesize("/home/a1962403/public_html/files/$file") . ' bytes';
$rownumber = $rownumber + 1;
//prints a table row
echo '<tr class="bottomline">';
echo "<td><input type='checkbox' name='checkbox[$rownumber]' value='[$rownumber]' </td>";
echo "<td>$file</td>";
echo "<td>$date</td>";
echo "<td>$size</td>";
echo '</tr>';
}
echo '</table>';
closedir($dir);
?>
</article>
</form>
</body>
</html>
From this, I have a submit button called 'deleteFile', which I am wanting to use to as I said for the moment, just get what is selected to ensure it works, but it's not actually giving me any output so any help would be greatly appreciated.
Your row formatting may be the problem
echo "<td><input type='checkbox' name='checkbox[$rownumber]' value='[$rownumber]' </td>";
Change it to:
echo "<td><input type='checkbox' name='checkbox[" . $rownumber . "]' value='". $rownumber . "' </td>";
And because your are numbering from 0 up you could also just use checkbox[] as a name.
It would help to this form live.
You are right to use isset when determining whether a checkbox is checked or not, but you are using differring names:
isset($_POST['checkbox'])
will return true if
<input type="checkbox" name="checkbox" />
is checked.
You have to refer to posted inputs using their names in the $_POST array.
In this case, you need to check for checkbox[$rownumber], which, as is seemingly trivial, requires you to know the row numbers when posting:
PHP code
if (isset($_POST["checkbox[$rownumber]"]))
{
// This checkbox is checked
}
If you don't know the exact input names, you might want to iterate through the $_POST array:
PHP code
foreach ($_POST as $input_name => $input_value)
{
if (strpos($input_name, 'checkbox') !== false)
{
// This input's name contains the substring 'checkbox'
}
}
Note the type-strict comparison at strpos.

Simple form submit to PHP function failing

I'm trying to submit two form field values to a PHP function, on the same page.
The function works perfect manually filling the two values.
<?PHP // Works as expected
echo "<br />"."<br />"."Write text file value: ".sav_newval_of(e, 45);
?>
On the form I must be missing something, or I have a syntax error. The web page doesn't fail to display. I found the below example here: A 1 Year old Stackoverflow post
<?php
if( isset($_GET['submit']) ) {
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
$result = sav_newval_of($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result of the form ?>
<form action="" method="get">
Input position a-s:
<input type="text" name="val1" id="val1"></input>
<br></br>
Input quantity value:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" value="send"></input>
</form>
Could it be the placement of my code on the form?
Any suggestions appreciated.
You need to name your submit button, or check for something else on your if(isset($_GET['submit'])) portion:
<form action="" method="get">
Input position a-s:
<input type="text" name="val1" id="val1" />
<br></br>
Input quantity value:
<input type="text" name="val2" id="val2" />
<br></br>
<input type="submit" name="submit" value="send" />
</form>
OR keep same form, but change php to:
<?php
if( isset($_GET['val1']) || isset($_GET['val2'])) {
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
$result = sav_newval_of($val1, $val2);
}
?>
You can you hidden field as:
<input type='hidden' name='action' value='add' >
And check on php by using isset function that form has been submitted.

Categories