Passing selected Value from options to a php variable - php

I want to create a form in which I access several tables and offer the user choices regarding the entries through these tables.
I have a "Systems" table from which the user can choose a system.
For this purpose I have a "Users" table, from which the user can choose a user.
This data should be selected and stored in the third table "Reports".
My code looks like this:
if (isset($_POST['submit'])) {
$systemId = $_POST['systemId'];
$userId = $_POST['userId'];
}
if ($db->addReport('reports', ["systemId" => $systemId, "userId" => $userId,)) {
echo("Entry added");
}
?>
<p>Create report</p>
<form action="" method="post">
<?php $entries = $db->getSystem(); ?>
<div class="form">
<label>System</label>
<select name="systemId" class="form-control">
<?php foreach ($entries as $option) : ?>
<option value="<?php ($option[0]) ?>" selected="<?php ($option[0]) ?>"> <?php echo($option[0]) ?> </option>
<?php endforeach; ?>
</select>
</div>
<input type="submit" name="submit" value="Submit">
</form>
I left out the part with the user for simplicity's sake, because I proceed exactly as I do with the system.
My problem is that an entry is made in the database, but the values are always "0". However, there are also entries in the database that do not have the value 0. The correct names are shown to me in the selection context, but what is actually written to the database is wrong.
So I cannot pass the correct value to the variable "systemId".
I tried several things on the internet, unfortunately nothing worked.
Notice: the connection to the database works fine. I don't have any problems with running the querys.

You're running the insert command even when the form hasn't been submitted. Just move that command inside the if statement which checks for the submitted data, so that it only runs in response to a suitable POST request.
if(isset($_POST['submit']))
{
$systemId = $_POST['systemId'];
$userId = $_POST['userId'];
if($db->addReport('reports',["systemId"=> $systemId, "userId"=>$userId,)){
echo("Entry added");
}
}

Related

How to achieve that the form will NOT resubmit and change the toggle status [duplicate]

I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}

Taking mySQL database input from HTML form with PHP

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

Displaying submitted data from database

What I want to do is when the user clicks submit, the data gets entered to the database and it will redirect me to like a Thank you page showing what the user has submitted.
code snippet: html code & php code:
<form action="ThankYouReport.html" method="post"
enctype="multipart/form-data">
<div>
<div class="container">
<label><input
type="checkbox" name="check[]" value="Beans">Beans</label>
<label><input type="checkbox" name="check[]" value="Apple" >
Apple</label>
</div>
</form>
<?php
require('config.php');
if(isset($_POST['sub']))
{
$checkbox1=$_POST['check'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1.",";
}
mysql_query("INSERT INTO `list` (`checked1`) VALUES ( ','$chk')") or
die(mysql_error());
}
?>
I looked around and saw that you had to change the form action, I did that but for some reason my data won't get entered in my database.
How would I go about displaying the data to another page.
I know there been many post on this site but none of them help me.
Try this and see the comments within:
<?php
session_start(); // always do this at the very top of your script
require('config.php');
if (isset($_POST['sub'])) {
$chk = implode(',',$_POST['check']); // shorter than using foreach
$sql = "INSERT INTO `list` (`checked1`) VALUES ('{$chk}')"; // just a way of storing a query to a variable
if(mysql_query($sql)) {
$_SESSION['success_msg'] = 'Successfully added items '.$chk; // store a message or whatever into a session variable
// FYI if you wrap a string with single quotes, you cannot use a variable within like in above query string, but have to be concatenated using a dot (.)
header('Location: http://www.example.com/ThankYouReport.html'); // redirect on success
} else {
die('Could not insert query'); // or print this message
}
}
?>
<form method="post" enctype="multipart/form-data"><!-- remove action attribute or use name of script this is in. -->
<div class="container">
<label><input type="checkbox" name="check[]" value="Beans"> Beans</label>
<label><input type="checkbox" name="check[]" value="Apple"> Apple</label>
</div>
</form>
EDIT (based on the comment)
If you want to transfer data from one script to another, especially for something simple as a thank you page or similar you can use php sessions. You need to turn your thank you page into a PHP script like so:
thanks.php
<?php
session_start();
?>
<div>
<?php echo $_SESSION['success_msg'];?>
</div>

Session Variable not sending to next page

I am trying to set a session variable for the location selected in the dropdown menu when the user hits submit. The goal is to pass this variable to another php page so that I can display the drop down option they chose along with two values associated with it from a MYSQL table.
Below is a section of my code from my first php file. It shows the dropdown that is created from a list of values from the MYSQL database along with where I am trying to set the session variable for the selected option.
session_start();
<form action="/locationsprocessing.php" method="post">
<select id="locations" name="locations"><? echo $option; ?></select>
<input type="submit" value="Submit" name="submit" id="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['locations'] = $_POST['locations'];
$_SESSION['animal'] = 'cat';
}
Below is my code from the second page where I call the session variables for display. As you can see I have input another variable for testing purposes. It is supposed to display "cat" and it does.
session_start();
echo $_SESSION['animal'];
echo $_SESSION['locations'];
It may also be important to note that locationsprocessing.php runs a redirect using header. But that is really all that file does.
Am I missing something? I have gone through countless different tuts and such and been staring at this code forever. I can not see why it wo
you need start session in every pages where you need to use session:
<form action="/locationsprocessing.php" method="post">
<select id="locations" name="locations"><? echo $option; ?></select>
<input type="submit" value="Submit" name="submit" id="submit">
</form>
<?php
if (isset($_POST['submit'])) {
session_start();
$_SESSION['locations'] = $_POST['locations'];
$_SESSION['animal'] = 'cat';
}
This may be going wrong: When you submit your form in the first piece of code from the questions, you are sending the data entered in the form to /locationsprocessing.php. You say that all that file does is redirecting to another page. That means the data entered in the form is effectively lost.
I think what you want to do is to remove the form processing code from the first piece of code, so with only this remaining:
session_start();
<form action="/locationsprocessing.php" method="post">
<select id="locations" name="locations"><? echo $option; ?></select>
<input type="submit" value="Submit" name="submit" id="submit">
</form>
Then place that removed piece of code in /locationsprocessing.php, like this:
session_start();
if (isset($_POST['submit'])) {
$_SESSION['locations'] = $_POST['locations'];
$_SESSION['animal'] = 'cat';
header('Location: ' . $destination);
}
$destination would be the path for the page with the second piece of code in the question.

php : Change forms Dynamically Respect to user input with out using a framework

I'm trying to create a form like : http://webhelpdesk.demo.solarwinds.com/helpdesk/WebObjects/Helpdesk.woa/wa/login?username=client&password=client&ui=client
The fields are changed according to the user's selection. The combinations are quite large. The form changes for almost all the selected values.
Is there a specific design pattern or some architectural guide line for creating such forms?
How can I implement such a form using PHP?
A pure PHP implementation would require 2 forms one to select the other but it would look a little something like this.
<?php
$formTypes = array("HR Form"=>"forms/hrform.php",
"Accounting Form"=>"forms/accounting.php");
$selectedForm = isset($_GET["form"])?$_GET["form"]:"HR Form"; // the else indicates the default
?>
<form name='formSelector' method='get'>
<select name='form'>
<?php foreach($formTypes as $label=>$form): ?>
<option value="<?= $label ?>"<?= $selectedForm == $label?" selected='selected':"" ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
<input type='submit' value='Select Form'/>
</form>
<?php include ($formTypes[$selectedForm]); ?>
for each of the forms you would have something like this...
=== forms/hrform.php ===
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// validate and process the form
// on successful process display confirmation and return
}
// show the form html
?>

Categories