Popup on if statement in php - php

I have a html form which looks like this:
<form action="submitOrder.php" method="get">
<select name="orderForm">
<?php
echo '<option value=" "> </option>';
while($row = \mssql_fetch_array($employeeOrderResult))
{
echo '<option value="'.$row[EMPLOYEE].'">'.$row[EMPLOYEE].'</option>';
}
?>
<option value="Gæst">Gæst</option>
<option value="Praktikant-01">Praktikant-01</option>
<option value="Praktikant-02">Praktikant-02</option>
<option value="Praktikant-03">Praktikant-03</option>
</select>
<br>
Vare: <input type ="text" name="varenr"><br>
Antal: <input type="text" name="antal"><br>
<input type="submit" value="Bestil">
</form>
It fetches som data from a database and adds some special guests.
Now, when it confirms it redirects to a page which has this code in it:
<?php
$ofAntal = $_GET['antal'];
$ofMedarbejder = $_GET['orderForm'];
$ofDato = date('Y-m-d H:i:s');
$ofVareNr = $_GET['varenr'];
$sql = "INSERT INTO Bestillinger(bestillingsAntal,medarbejder,dato,vareNr) VALUES('$ofAntal','$ofMedarbejder','$ofDato','$ofVareNr')";
$validation = mysql_query($sql, $MySQLcon);
if(!$validation)
{
die('Couldnt enter data ' . mysql_error());
}
echo 'Entered data succesfully';
?>
Now, I need a confirmation popup of some kind, if the amount (ofAntal) is above 1, and Ive looked into several solutions. The problem is i started working with PHP tuesday morning, and i cant find a solution that works for me.
All it has to do, is submit the data is yes is clicked, and cancel it if the user clicks no/cancel. This is ofc done in an IF statement, thats not the issue, the issue is how to implement it properly.
ANY help is highly appreciated :)

Use javascript confirm box on onclick attribute for submit button. It will give you yes and cancel options.
<input type="submit" value="Bestil" onclick="confirm("Are you sure ?");">
Orelse
You can write a function in javascript to check that
<input type="submit" value="Bestil" onclick="myfunct();">
function myfunct(){
if(document.getElementById("antal").value > 1)
confirm("Are you sure");
return true;
}

Related

check if the radio button clicked is the answer stored in database

I am designing an online test series. I want when an answer is selected by the user, it should be validated by the answer stored in the database and move to next question on the basis of correct and incorrect choice. I am using php and mysqli. Can someone tell me how to get the id of the user selected answer and validate with the correct answer? This is html
<form method="POST" name="try" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">;
<h4> <?php echo $_SESSION["Question"] ?> </h4>
<input type="radio" name="options" value="A" id="A"> <?php echo $_SESSION["OpA"] ?> </input><br>
<input type="radio" name="options" value="B" id="B"> <?php echo $_SESSION["OpB"] ?> </input><br>
<input type="radio" name="options" value="C" id="C"> <?php echo $_SESSION["OpC"] ?> </input><br>
<input type="radio" name="options" value="D" id="D"> <?php echo $_SESSION["OpD"] ?> </input><br>
<input type="radio" name="options" value="E" id="E"> <?php echo $_SESSION["OpE"] ?> </input><br>
<button type="button" class="btn" name="submit" value="submit" >Submit</button>
<?php
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db( $conn , 'myDB' );
echo "<form method='get' action=" .htmlspecialchars($_SERVER['PHP_SELF']) . ";>";
$sql = "SELECT * FROM QUANT_MEDIUM ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$_SESSION['ans'] = $row['Correct'];
$_SESSION['Question'] = $row['Ques'];
$_SESSION['OpA'] = $row['Option_A'];
$_SESSION['OpB'] = $row['Option_B'];
$_SESSION['OpC'] = $row['Option_C'];
$_SESSION['OpD'] = $row['Option_D'];
$_SESSION['OpE'] = $row['Option_E'];
}
}
?>
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit']))
{
if (isset($_POST['options']))
{
$radio_input = $_POST['options'];
echo $radio_input;
}
}
else
{
echo "wrong";
}
?>
Before looking at a possible solution you must determine where you want the check to be done. You tagged the question "jquery" so I guess you're interested in a clientside option as well as a serverside option.
Client side
If you want to do the check clientside, depending on how you implement it, the user might be able to see the correct answer by inspecting the code. If this is no problem, you can have the fastest user experience by checking it clientside.
The most simple option, but easy to "hack" would be to add an extra attribute to the radiobutton. Something like "correct" or so. When the submit button is clicked you can use jquery to check if the selected radio button has the "correct" attribute and do whatever action you want with that info.
You can also have the frontend do a query to the server to check. This would be more secure, but the method described above is the simplest.
Server side
If you want the client to have no possible way of getting the answer beforehand, you're best doing the check serverside. Here the "onclick"you have on the submit button can be removed and have the form do an actual post to the server, and have the server do a check and display the next question if the given answer is correct.
In order to have the server know what question is being checked you could add a hidden field with the question ID.
The validation can be done on the server side using php. The solution would be not to use a submit button and let the server take the responsibility of checking what is submitted to the server. So the submit button can be replaced by the following :
<input type="submit" name="submit" value="submit" class="btn"></input>
And the validation can be done using the following piece of code :
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit']))
{
if (isset($_POST['options']))
{
$radio_input = $_POST['options'];
//echo $radio_input;
if($radio_input == $_SESSION['ans'])
echo "correct";
else
echo "incorrect";
}
}
?>

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.

form select with ajax

I'm building a bug tracker tool.
When you create a project, you can change the project status (open, in progress & finished) on the project page using this select form:
<form action="classes/projectStatus.class.php" method="post">
<label> Change Project Status </label>
<select name="status" id="status">
<option value="Open">Open</option>
<option value="In Progress">In Progress</option>
<option value="Finished">Finished</option>
</select>
<input type='hidden' name='hdnID' value="<?php echo $id;?>">
<input class="small button" value="Change Status" type="submit">
</form>
This is the projectStatus.class.php file:
$status = $_POST['status'];
$id = $_POST['hdnID'];
$sql="UPDATE projects SET status = '$status'";
$result = mysql_query($sql);
$result = mysql_real_escape_string($sql);
if($result){
header('Location: ../projectpage.php?id='.$id);
} else {
echo "There is something wrong. Try again later."; }
mysql_close();
How can I do this with AJAX?
Could anybody provide me with some right code?!
I know the form isn't sql injection proof and I don't use mysqli, I will change this, but first I'd like to have an answer :).
Thanks!
I would use jquery, which will solve a lot of compatibility issues.
There is example code here on the jquery site: http://api.jquery.com/jQuery.post/
You'll want to use jQuery's $.post() function. You should check out the docs here for a ton of examples. So what you could do is change
<form action="classes/projectStatus.class.php" method="post">
to
<form onsubmit="return submit();">
and then define submit as
function submit()
{
$.post('classes/projectStatus.class.php', {
"status": $('#status').val(),
"hdnID": $('#hdnID').val()
}, function(response) {
//your callback function
});
return false;
}
This code is untested and might not work, but it's just meant to give you an idea of what to do. Let me know if this makes sense or if you have any questions :)

get selected value of a drop down which is populated with results from an SQL query

So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:
<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
<input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
<select name="Name_dropdown" id="name_dropdown" style="width: 200px" >
<?php
$ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";
$ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());
while ($row= mysql_fetch_array($ClientName_Result)){
echo "<option> $row[FullName] </option>";
}
?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>
In your ClientDetails.php file the value will be available using,
$name = $_POST['Name_dropdown'];
If you need to change a setting in the form document before submitting you can use jQuery. Something like
$('#name_dropdown').change(function(){
var option = $(this.options[this.selectedIndex]).val();
});

PHP get input , radio , selection data and insert into MySQL table

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

Categories