I have a form that has a field whose value is from a php calculation. The Calculation is just basic arithmetic involving purely whole numbers. But there is a scenario where the value will be zero. So the form assumes that that filed has been left empty.
How can i go round that ?
Here is a sample of code.
if (
isset($_POST['input1']) &&
isset($_POST['input2']) &&
isset($_POST['ans'])
)
{
// CHECKING IF ANY OF THE FIELDS WERE LEFT EMPTY
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$ans = ($input1)-($input2);
$ans_set = 0;
if ($ans === $ans_set ) {
# code...
//echo "Same";
$ans = '0';
} else {
# code...
//echo "Different";
echo "Check data types";
}
if (
!empty($input1) &&
!empty($input2) &&
!empty($ans)
)
{
$query = "INSERT INTO formaths VALUES ( 'NUll', NOW(),
'".mysql_real_escape_string($input1)."',
'".mysql_real_escape_string($input2)."',
'".mysql_real_escape_string($ans)."' )";
$query_run = mysql_query($query);
if ( $query_run )
{
//header("Location:". __DIR__."../registration_success.php");
echo "<p class='echo'>Data entry was successful.</p>";
}
else
{
echo "<p class='echo'>It seems that we couldn't save that at this time.</p>";
}
}
else
{
echo "<p class='echo'>Please make sure all fields are filled and are correct.<br/>You must fill in the area field last!</p>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="formaths.php" method="POST">
<input name="input1" type="text" autofocus/>
<input name="input2" type="text"/>
<input name="ans" type="text" value="<?php if (isset($ans)) { echo $ans; }?>" readonly />
<input type="submit" value="DO IT" />
</form>
enter code here
</body>
</html>
Related
All I am trying to do is escape html injection into my input text boxes. Am I not using htmlentities correctly?
Code:
<?php
require_once "pdo.php";
// Demand a GET parameter
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die('Name parameter missing');
} else {
$username = $_GET['name'];
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$year = isset($_POST['year']) ? $_POST['year'] : '';
$mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
$make = isset($_POST['make']) ? $_POST['make'] : '';
$failure = false;
$success = false;
if ( isset($_POST['make']) && isset($_POST['year'])
&& isset($_POST['mileage'])) {
//$year = $_POST['year'];
//$mileage = $_POST['mileage'];
//$make = $_POST['make'];
if ( strlen($make) < 1){
$failure = "Make is Required";
} else {
if (is_numeric($year) and is_numeric($mileage) ){
error_log("year is a number ".$_POST['year']);
error_log("Mileage is a number ".$_POST['mileage']);
$sql = "INSERT INTO autos (make, year, mileage)
VALUES (:make, :year, :mileage)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $make,
':year' => $year,
':mileage' => $mileage));
$success = "Record Inserted";
} else {
$failure = "Mileage and Year must be numeric";
error_log("year or mileage is not a number year=".$_POST['year']);
error_log("Mileage or year is not a number mileage=".$_POST['mileage']);
}
}
}
if ( isset($_POST['delete']) && isset($_POST['auto_id']) ) {
$sql = "DELETE FROM autos WHERE auto_id = :zip";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':zip' => $_POST['auto_id']));
}
$stmt = $pdo->query("SELECT make, year, mileage, auto_id FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Douglas Osborne's Automobile Tracker</title>
</head>
<body>
<table border="0">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['year']);
echo(" /");
echo("</td><td>");
echo($row['make']);
echo("</td><td>");
echo($row['mileage']);
echo(" miles");
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="auto_id" value="'.$row['auto_id'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
<body>
<div class="container">
<h1>
<?php
if ( isset($_REQUEST['name']) ) {
echo "<p>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</p>\n";
}
?>
</h1>
<p>
<?php
// Note triple not equals and think how badly double
// not equals would work here...
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
</p>
<form method="post">
<p>Make:
<input type="text" name="make" size="60" value="<?= htmlentities($make) ?>"/>
</p>
<p>Year:
<input type="text" name="year" value="<?= htmlentities($year) ?>"/>
</p>
<p>Mileage:
<input type="text" name="mileage" value="<?= htmlentities($mileage) ?>"/>
</p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<p>
</ul>
</div>
</html>
Output wont escape see screenshot:
Adding htmlspecialchars to (make) gave me the result I was looking for. Thanks for anyone's attempt to help me.
I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";
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']);
?>
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'];
So I'm working on this password reset form. Where a user clicks on a link sent to their email and they are taken to a webpage to enter a new password. When they submit the form 3 variables (password, key, & email) are passed to my functions file to update the password for the user. The password itself is being posted, but the email and key are not. I did a vardump to see what is actually being sent and its just displaying the code in the values of email/key on the form. I'm not sure what I'm doing wrong.
EDIT
So I figured out that the email/key were not being passed to the updateUserPassword() function. I posted the new correct form code below. SOLVED
<?php session_start();
include("include/DB_Connect.php");
include("include/DB_Functions.php"); // Connect to database server(localhost) with username and password.
mysql_select_db("android_api") or die(mysql_error()); // Select registration database.
$show = 'emailForm'; //which form step to show by default
if (isset($_POST['subStep']) && !isset($_GET['a']))
{
switch($_POST['subStep'])
{
case 1:
//we are submitting a new password (only for encrypted)
if ($_POST['email'] == '' || $_POST['key'] == '') header("location: forgotpw.php");
if (strcmp($_POST['password'],$_POST['pw1']) != 0 || trim($_POST['password']) == '')
{
$error = true;
$show = 'recoverForm';
} else {
$error = false;
$show = 'recoverSuccess';
updateUserPassword($_POST['email'],$_POST['password'],$_POST['key']);
var_dump($_POST['email'],$_POST['password'],$_POST['key']);
}
break;
}
} elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
$show = 'invalidKey';
$result = checkEmailKey(urldecode(base64_decode($_GET['email'])),$_GET['key']);
if ($result == false)
{
$error = true;
$show = 'invalidKey';
} elseif ($result['status'] == true) {
$error = false;
$show = 'recoverForm';
$securityUser = $result['email'];
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="assets/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header"></div>
<div id="page">
<?php switch($show) {
case 'recoverForm': ?>
<h2>Password Recovery</h2>
<p>Welcome back, <?php echo getUserName($securityUser=='' ? $_GET['email'] : $securityUser); ?>.</p>
<p>In the fields below, enter your new password.</p>
<?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="fieldGroup"><label for="password">New Password</label><div class="field"><input type="password" class="input" name="password" id="password" value="" maxlength="20"></div></div>
<div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field"><input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
<input type="hidden" name="subStep" value="1" />
<input type="hidden" name="email" value="<?php echo $securityUser=='' ? $_POST['email'] : $securityUser; ?>" />
<input type="hidden" name="key" value="<?php echo $_GET['key']=='' ? $_POST['key'] : $_GET['key']; ?>" />
<div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
<div class="clear"></div>
</form>
<?php break; case 'invalidKey': ?>
<h2>Invalid Key</h2>
<p>The key that you entered was invalid. Either you did not copy the entire key from the email, you are trying to use the key after it has expired (3 days after request), or you have already used the key in which case it is deactivated.<br /><br />Return to the login page. </p>
<?php break; case 'recoverSuccess': ?>
<h2>Password Reset</h2>
<p>Congratulations! your password has been reset successfully.</p><br /><br />Return to the login page. </p>
<?php break; }
ob_flush();
$mySQL->close();
?>
</div>
</body>
</html>
Here is my function code:
function updateUserPassword($email,$password,$key)
{
global $mySQL;
if (checkEmailKey($email,$key) === false) return false;
if ($SQL = $mySQL->prepare("UPDATE `users` SET `encrypted_password` = ? WHERE `email` = ?"))
{
$password = md5(trim($password) . PW_SALT);
$SQL->bind_param('ss',$email,$password);
$SQL->execute();
$SQL->close();
$SQL = $mySQL->prepare("DELETE FROM `recoveryemails_enc` WHERE `Key` = ?");
$SQL->bind_param('s',$key);
$SQL->execute();
}
}