Im trying to understand php a little better so Im making an application that converts different units. In my code I ask the user to enter a value for units of length, volume, and weight, then check a multiple checkboxes to convert what unit they want. I have everything working except for when I enter no input in a input box I get a warning A non-numeric value encountered in " ". So my question is how do I stop this warning from showing and just have it say you forgot to enter an input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="convert_units2.php" method="POST">
<?php
//use from other php code
// require("form_functions.php");
//
// include("form_functions.php");
function generate_options_pulldown($options){
echo '<select name = "' . $options["title"] . '_unit">';
foreach($options["list"] as $opt){
echo '<option value="' . $opt . '">' . $opt . '</option>';
}
echo '</select>';
}
function generate_options_checkbox($options){
foreach($options["list"] as $opt){
echo '<lable><input type ="checkbox" name="'. $opt . '">' .$opt .'</label>';
}
}
function generate_conversion_form($units){
echo '<input type="text" size="10" name="' . $units["title"] . '_val"> ';
generate_options_pulldown($units);
echo "-->";
generate_options_checkbox($units);
}
//
$length_units = array("title"=>"length","list"=>array("meter","mm","cm","km"));
$volume_units = array("title"=>"volume","list"=>array("liter","oz","gallon"));
$weight_units = array("title"=>"weight","list"=>array("gram","mg","kg"));
if ($_SERVER["REQUEST_METHOD"] == "GET"){
generate_conversion_form($length_units);
echo "<p>";
generate_conversion_form($volume_units);
echo "<p>";
generate_conversion_form($weight_units);
echo '<p><input type="submit" value="Convert"></p>';
}
else{//Post
// var_dump($_POST);
$length_units_conversion_table = array("meter"=>1,"mm"=>1000,"cm"=>100,"km"=>0.001);
$from_unit = $_POST["length_unit"];
$val = $_POST["length_val"];
$meter = $val / $length_units_conversion_table[$from_unit];
foreach($length_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$meter * $rate, $unit);
}
echo '<br>';
$volumn_units_conversion_table = array("liter"=>1,"oz"=>33.8,"gallon"=>0.264);
$from_unit = $_POST["volume_unit"];
$val = $_POST["volume_val"];
$liter = $val / $volumn_units_conversion_table[$from_unit];
foreach($volumn_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$liter * $rate, $unit);
}
echo '<br>';
$weight_units_conversion_table = array("gram"=>1,"mg"=>1000,"kg"=>0.001);
$from_unit = $_POST["weight_unit"];
$val = $_POST["weight_val"];
$gram = $val / $weight_units_conversion_table[$from_unit];
foreach($weight_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$gram * $rate, $unit);
}
}
?>
</form>
</body>
</html>
you can check if the value is numeric using the function is_numeric() (https://www.php.net/manual/en/function.is-numeric.php)
if(!is_numeric($_POST["volume_val"])) { ...} )
For the specific case where no value has been set, you can either check that the value is not an empty string,
if( $_POST["volume_val"] == '') {...}
or convert an empty string to zero
$volume_val = empty($_POST["volume_val"]) ? 0 : $_POST["volume_val"];
For the empty field alert, you can use the required attribute in the input, so when you submit the form you'll get the "Field required" warning and the form won't submit.
Then, in the POST part of your code, you can test $_POST["length_unit"] for empty:
if (empty(trim($_POST["length_unit"])))
if this is true then ... you can either treat this as 0 or just send a warning.
You can also test for numeric value before processing:
if (is_numeric($_POST["length_unit"]))
Related
I created an HTML application form for my employer so that applicant's can apply online. However, I'm running into some issues with the PHP bit. I'd like for it to send me an email containing ALL of the forms field names along with their values (even if the value is left blank). It needs to be in this specific format so that I can quickly 'convert' that data programmatically from the email into an HCL Notes form.
However, when a checkbox on my HTML form is left unchecked, it is not sent to the $_POST array at all, which then obviously ends up breaking the bit that converts it as it can't find the correct field names.
I know this is a strange and very specific issue, but does anyone have any ideas as to how I can go about this successfully?
My PHP code currently (removed the parameters at the top for privacy):
<?php session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results</title>
</head>
<body>
<?php
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = '';
// Your email address. This is where the form information will be sent.
$emailadd = '';
// Where to redirect after form is processed.
$url = '';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
$time = time();
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// handle the error accordingly with your other error checking
// or you can do something really basic like this
die('The code you entered was incorrect. Go back and try again.');
}
foreach ($_POST as $key => $value)
{
if ($key != "captcha_code"){
$j = strlen($key);
if ($j >= 40){echo "Name of form element $key cannot be longer than 39 characters";die;}
$j = 40 - $j;
for ($i = 1; $i <= $j; $i++)
{$space .= ' ';}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
}
$text .= 'END OF APPLICATION';
mail($emailadd, $subject, $text, 'From: ');
echo '<script>alert("Application successfully submitted.");</script>';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
</body>
</html>
Here's how the emails look, I need it to be just like this but with ALL fields regardless of if they have values or not:
Create an array that lists all the fields that should be in the email. Then instead of looping through $_POST, loop through that array. Display the corresponding $_POST field if it's filled in, otherwise show a blank value.
$fields = ['ReasonForReferral', 'FirstName', 'MiddleName', ...];
foreach ($fields as $field) {
$conc .= "$field: " . (isset($_POST[$field]) ? str_replace($_POST[$field], "\n", $line) : '') . $line;
}
I'm trying to add the parameter cs with a value of 1 to the url using a form and hidden type input. When I execute this, I have a simple if statement that checks to see if $_GET['cs'] is = to 1, but I get a Notice: Undefined index. I'm a php beginner, any help, explanations, or alternatives is very much appreciated.
echo '<form>';
echo '<input type="hidden" name="cs" value="1">';
echo '</form>';
if($_GET['cs'] == 1) {
echo'working';
}
else {
echo 'not working';
}
Only after form is submitted you will see 'cs' in $_GET array.
The $_GET array contains all parameters on the URL line.
For example if a URL is: https://example.com?param1=1¶m2=2
You will get a $_GET array with two entries ('param1' and 'param2') with values 1 and 2.
You should add a check using the isset function (https://www.php.net/manual/en/function.isset.php). Otherwise it will try to access the parameter if it isn't sent. In your case the parameter was probably not sent.
Url in html:
test the get method
The url test
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
Full code:
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get varaible</title>
</head>
<body>
test the get method
</body>
</html>
I have a very simple php site that and am attempting to make it a little more dynamic. Previously, I required user to click on a link to open a new page containing several images together with some 'submit' buttons. Pressing a button called a php file that saved some information in a text box. This was working fine. However, I have now made the content a little more dynamic so that the user chooses an item from a popupmenu to update content in the same page. However, now the submit buttons produced dynamically do not seem to work. I am quite new to web development generally so not sure why this should be the case. Any help much appreciated.
This is the index.php file that populates the list box and sets up the page to dynamically manage the content.
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Title</title>
<meta name="language" content="en" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<?php
$myDirectoryStr = "trialImages/";
// open this directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
?>
<?php
// loop through the array of files and print them all in a list
$cnt = 0;
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){
$dateStr[$cnt] = substr($dirArray[$index], 0, 8 );
$cnt++;
}
}
// count elements in array
$indexCount = count($dateStr);
// find unique dates
$dateStrUnique = array_values( array_unique( $dateStr, SORT_STRING ) );
// count elements in array
$indexCount = count($dateStrUnique);
echo '<form>';
echo '<select name="dates" onchange="showImages(this.value)">';
echo '<option value="">select date ...</option>';
for($index=0; $index < $indexCount; $index++) {
echo '<option value="' . $dateStrUnique[$index]. '">' . $dateStrUnique[$index] . '</option>';
}
echo '</select>';
echo '</form>';
?>
<br>
<div id="imageTable"><b> image information will be displayed here ... </b></div>
</body>
</html>
'''
This is the dispData.php file that produces the dynamic content used to update the div tag and containing the submit buttons and images
'''php
<?php
// recover some information
$imageDateTarget = $_GET['imageDate'];
// image directory
$myDirectoryStr = "trialImages/";
// open directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
//count elements in array
$indexCount = count($dirArray);
echo '<table class="fixed">
<col width="200px">
<col width="200px">
<col width="100px">';
// loop through the array of files and display them in table
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){ // input image place in first column
// image date
$imageDate = substr($dirArray[$index], 0, 8 );
// if image date the same as selected date then display image
if ( strcmp( $imageDateTarget, $imageDate ) == 0 ) {
echo '<tr>';
echo '<td>' . $dirArray[$index] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td height=400><img src="' . $myDirectoryStr . $dirArray[$index] . '" class="rotate90" " alt="Image" border=3 height=200 width=400></img></td>';
echo '<form action="writeNotes.php" method="POST">';
//search for matching image notes if they exist and display
$indexImageNotes = array_search( $imageDate . 'notes.txt', $dirArray );
if ($indexImageNotes){
$notes = file_get_contents($myDirectoryStr . $imageDate . 'notes.txt'); // read contents into string
echo '<td><textarea name = "notes" rows = "26" cols="30">' . $notes . '</textarea></td>';
}
else {
echo '<td><textarea name = "notes" rows = "26" cols="30">add some comments here ...</textarea></td>';
}
echo '<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "' . $myDirectoryStr . $imageDate . '"></input></form></td>';
echo '</tr>';
}
}
}
?>
'''
And this is the writeNotes.php function that saves the text notes and should be called when the submit buttons are pressed
'''php
<?php
print_r("I am here");
$file = $_POST["imageDate"] . 'notes.txt';
$data = $_POST["notes"];
file_put_contents($file, $data);
?>
'''
Part of the problem is that I don't get any error messages, just a failure to execute the writeNotes.php function
I think there must be some mistakes in my earlier code as I have attempted a further simplified version and this seems to work. I simply populate a popupmenu below
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="dates" onchange="showImages(this.value)">
<option value="">select date ...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<div id="imageTable"><b> information will be displayed here ... </b></div>
</body>
</html>
'''
And return the dynamic content here
'''php
<?php
echo '<form action="writeNotes.php" method="POST">
<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "a_value"></input></form></td>';
?>
'''
And the writeNotes.php function
'''php
<?php
$file = $_POST["imageDate"];
print_r($file);
//header("Location: index.php"); //note there must be no output before using header
?>
'''
This seems to work without a problem. Apologies for asking the earlier question and thanks again for comments.
I'm trying to create my first function in PHP, a drop down. It's almost working, but when I submit/post the data the options with a space in it will only show the first word in the output.
In the example I have 'First Name' as an option in the drop down list. When I hit submit, the output will only be 'First'. When I change 'First Name' to 'First-Name' it works, the output is 'First-Name'. So I think I need to add quotes somewhere in the code so that it is handled as a string??
Hope someone can help me out, I'm so close to what I want.
<!DOCTYPE HTML>
<html>
<body>
<?php
include('db_functions.php');
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = clean_input($_POST['first_name']);
}
//drop down function
function dropdown($name, $options) {
$dropdown = '<select type="text" name='.$name.'>'."\n";
$rows = $options;
if($rows === false) {
$error = db_error();
}
$totalrows = count($rows);
for ($x = 0; $x < $totalrows; $x++) {
$dropdown .= '<option value=' . $rows[$x][$name] . '>' . $rows[$x][$name] . '</option>'."\n";
}
$dropdown .='</select>'."\n";
return $dropdown;
}
echo '<form action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
//start dropdown
echo 'First Name:';
$name = 'first_name';
$options = db_select("SELECT DISTINCT first_name FROM nametable GROUP BY first_name ORDER BY first_name ASC LIMIT 20");
echo dropdown($name, $options);
//end dropdown
echo '<input type="submit" name="submit" value="Submit">';
echo '</form>';
echo $fName;
?>
</body>
</html>
Your code is writing
<option value=First Name>
The space ends the value, so Name is a separate attribute. You need to put the value in quotes, so it's
<option value="First Name">
The code should be:
$dropdown .= '<option value="' . $rows[$x][$name] . '">' . $rows[$x][$name] . '</option>'."\n";
I have a single page php application to generate an 8 digit number, user inputs a value and page generates another value, both values are inserted into mysql db and displaying the generated value in an input box at a single button click. Insertion is happening, but generated value is not displaying in the inputbox at the first time, I also tried session its not helping too.
here is my php code,
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<?php
if(isset($_POST['luckyButton']) && $_POST['myLuckyNumber'] != ""){
//sleep(20);
$myLuckyNum = $_POST['myLuckyNumber'];
$resultmyLuckyNum = mysql_query("SELECT * FROM lucky where luckyNum='$myLuckyNum'") or die(mysql_error());
if (mysql_num_rows($resultmyLuckyNum) > 0) {
while ($rowmyLuckyNum = mysql_fetch_array($resultmyLuckyNum)) {
$generatedNumber = $rowmyLuckyNum["generatedNum"];
}
}else{
$gen = getGen();
$resultGenNum = mysql_query("INSERT INTO lucky (slno, luckyNum, generatedNum) VALUES ( NULL, '$myLuckyNum', '$gen')");
if (mysql_num_rows($resultGenNum) > 0) {
$generatedNumber = $gen;
}
}
}
?>
<form action="" method="post">
<input type="text"class="inputs" name="myLuckyNumber" onClick="this.select();" placeholder="Enter You Lucky Number" value="<?php echo $myLuckyNum; ?>" />
<input type="submit" class="css_button" name="luckyButton" value="Check"/>
</form>
</div>
<br><br><br>
<?php
if($generatedNumber != ""){
echo '<input type="text" name="myLuckyNumber" onClick="this.select();" id="generatedNumber" readonly="true" value="' . $generatedNumber . '" />';
}
echo '<p id="errText"> ' . $err . ' </p>';
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
function getGen(){
$gen1 = random_string(8);
$result = mysql_query("SELECT * FROM lucky where generatedNum='$gen1'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
if($row["generatedNum"] == $gen1){
getGen();
}
}
}else{
//echo $gen1;
return($gen1);
}
}
?>
</body>
</html>
my table,.
CREATE TABLE `lucky` (
`slno` int(11) NOT NULL,
`luckyNum` text NOT NULL,
`generatedNum` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
The problem with your code is that mysql_num_rows will return either 0 or 1, use it like
if($resultGenNum === 1){
$generatedNumber = $gen;
}
You are using mysql_num_rows in a wrong way. When you run insert query, it does not return rows, it returns true or false (Boolean). When it will return true, you will get 1 (as $resultGenNum).
use this instead:
if ($resultGenNum === 1){
$generatedNumber = $gen;
}
Instead of using if ( $generatedNumber != "" ), perhaps you should try something like if ( isset( $generatedNumber ) ).
If $generatedNumber doesn't exist (which it doesn't if nothing was posted to the script), then the comparison will fail (in fact, you're probably getting a PHP error).
Of course, that leads us to the next problem - if nothing is posted to the script, you don't generate a number. So of course, if you don't generate a number, there is no number to display. So you should structure your code in such a way that a random number is always generated - regardless of whether a post variable was received or not.