Value of post does not update - php

I have created a reservation form. The user has the option when selecting a residence option from the drop down menu to not choose one, so the value would be 'Select One...'. If they do not select a residence area, once they submit the form it brings them to another page which gives them a drop down list of the options they have for residence areas based on their class and preferences. The results from the form print out on the third page with their name, gender, residence area, etc. The problem is that I retrieve the residence area by using $_POST["dorm"]. This works when the user does select a residence area, but if they do not, then the $_POST doesn't seem to update and reads as 'Select One...'.
Here is my code for the page that gives the user their residence area options:
<html>
<?php
require 'sql_helper.php';
echo " <form action = \"results2.php\" method = \"post\">\n<br> ";
//Read the information entered on the index page
$specialNeeds = isset($_POST["specialNeeds"]);
$laundry = isset($_POST["laundry"]);
$fullyEquippedKitchen = isset($_POST["fullyEquippedKitchen"]);
$class = $_POST["class"];
$dorm = $_POST["dorm"];
//If user did not choose a dorm
if ($dorm == "Select One...") {
$sql = "SELECT name, roomsAvailable FROM $dormTable WHERE class = $class || class = 'Select One...'";
if($result = mysqli_query($conn, $sql)) {
$numRows = mysqli_num_rows($result);
echo " <strong>Residence Areas</strong>\n ";
echo " <select name = dorm> \n";
for ($i = 0; $i < $numRows; $i++){
$aDorm = mysqli_fetch_assoc($result);
$dormName = $aDorm['name'];
$dormAvailable = $aDorm['roomsAvailable'];
if($dormName != 'Select One...'){
echo "<option value = \"$dormName\" > $dormName ($dormAvailable)</option>\n";
}
elseif ($dormAvailable == 0 && $dormName != 'Select One...'){
echo "<option value = \"$dormName\" disabled=\"disabled\"> $dormName </option> \n";
}
elseif ($dormName == 'Select One...'){
echo "<option value = \"$dormName\" disabled=\"disabled\" selected = \"true\"> $dormName </option> \n";
}
}
echo "</select>\n<br><br>";
}
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\" ><?php echo print_r($_POST) ?>";
}
echo " <input type = \"submit\" value = \"Submit\"> \n <br> ";
}
//If user did choose a dorm
else {
$sql = "SELECT * FROM $dormTable WHERE name = '$dorm'";
if ($result = mysqli_query($conn, $sql)) {
$dormRecord = mysqli_fetch_assoc($result);
if ($class == $dormRecord['class']) {
unset($errorString);
// check preferences
if ($fullyEquippedKitchen) {
if (!$dormRecord['fullyEquippedKitchen']) {
$errorString = "$dormRecord[name] does not have a kitchen.\n";
echo $errorString;
echo 'Go back to the previous page to re-enter your preferences.<br><br>';
echo 'Go back<br><br>';
}
else{
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\"> <?php echo print_r($_POST) ?>";
}
echo "Your preferences are a match!<br>";
echo " <input type = \"submit\" value = \"Submit\"> \n <br> ";
}
}
else{
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\"> <?php echo print_r($_POST) ?>";
}
echo "Your preferences are a match!<br>";
echo " <input type = \"submit\" value = \"Submit\"> \n <br> ";
}
}
else {
$errorString = "You cannot live in $dormRecord[name] because of your class status.\n";
echo $errorString;
echo 'Go back to the previous page to re-enter your preferences.<br><br>';
echo 'Go back<br><br>';
}
}
else {
echo "something is wrong: ".mysqli_error($conn);
die;
}
?>
</form>
<?php
}
?>

Related

How to make a loop statement, to get the value from the previous page?

I'm setting up an online quiz/exam page in my website on localhost (for education purposes only). But when checking for the answer it only checks for the second question for the right answer.
e.g There are 2 questions. I chose both correct answers, but at the next page it shows that I got 1 out of 2. ?
I have tried using POST/GET method as well...
but still the same
Students taking the quiz (Question).php
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id =
$quiz_id");
if (!isset($_POST['Submit']) || ($_POST['Submit'] != 'Mark')) {
while ($row = mysqli_fetch_array($display)) {
echo "<form method=post action='score.php?quiz_id=";
echo $row['quiz_id'];
echo "'>";
echo "<table border=0>";
$id = $row["question_id"];
$question = $row["questions"];
$opt1 = $row["option1"];
$opt2 = $row["option2"];
$opt3 = $row["option3"];
$opt4 = $row["option4"];
$answer = $row["answer"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "
<tr>
<td>$opt1 <input type=radio name='q$id' value=\"$opt1\"></td>
<td>$opt2 <input type=radio name='q$id' value=\"$opt2\"></td>
<td>$opt3 <input type=radio name='q$id' value=\"$opt3\"></td>
<td>$opt4 <input type=radio name='q$id' value=\"$opt4\"></td>
</tr>
";
}
echo "</table>";
echo "<input type='Submit' name='Submit' value ='Mark'>";
echo "</form>";
}
?>
Score.php (marking the results)
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
if ($_POST['Submit']) {
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id = $quiz_id");
while ($row = mysqli_fetch_array($display)) {
$id = $row["question_id"];
$answer = $row["answer"];
$score = 0;
$total = mysqli_num_rows($display);
while ($result = mysqli_fetch_array($display)) {
$answer = "$result[answer]";
$q = "q$result[question_id]";
$q = trim($q);
if ($_POST[$q] == $answer) {
$score++;
}
}
echo "<p align=center><b>You scored $score out of $total</b></p>";
echo "<p>";
}
}
?>
I expect the results to be 2 out of 2.
But it is showing only 1 out of 2.
UPDATE
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
//echo 'from form: '.$_POST['q14']; // from form
if ($_POST['Submit']) {
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id =
$quiz_id");
while ($result = mysqli_fetch_array($display)) {
$id = $result["question_id"];
$answer = $result["answer"];
$score = 0;
$total = mysqli_num_rows($display);
$answer = $result['answer'];
$q = $result['question_id'];
echo 'answer: '.$answer;
//echo $q;
//$q = trim($q);
/* if ($q == $answer) {
$score++;
//echo "<p align=center><b>You scored $score out of $total</b></p>";
//echo "<p>";
}
}
?>

Allow only 1 POST of each dropdown value in PHP form

I have a simple PHP form to insert "models" (in dorpdown) with a price.
The thing I want to do is that you can only post model 1 once and model 2 once etc..
So if you choose model 1 in the dropdown and post it and try it again that it doesn't allow you because you already posted model 1.
sorry for my bad English
<select name="model">
<?
$modellen[1]= "Model 1";
$modellen[2]= "Model 2";
$modellen[3]= "Model 3";
foreach ($modellen as $key => $value)
{
echo "<option value='".$key."''>".$value."</option>";
}
?>
</select>
if(isset($_POST['toevoegen']))
{
$prijs = Safesql($_POST['prijs']);
$moment = date("Y-m-d h:i:sa");
$kiesmodel = Safesql($_POST['model']);
if(!$mysqli->query("INSERT INTO prijzen (prijs, created, model) VALUES (".$prijs.",'".$moment."' , '".$kiesmodel."')")) {echo $mysqli->error;}
else{ echo "het toevoegen is gelukt";}
Laden(0);
}
//show records from database
if ($query = $mysqli->query("SELECT * FROM prijzen")) { echo $mysqli->error;}
if ($query->num_rows >= 1)
{
while($row = $query->fetch_assoc())
{
?><tr><td><form action="index.php" method="post">
<? echo "Model" . " " . $row['model']; ?><img src="delete.png">
<img src="edit.png"><?
echo " prijs:" . $row['prijs']. "<br>" ."";?><?
}
}
try add validation before insert,
if(isset($_POST['toevoegen']))
{
$prijs = Safesql($_POST['prijs']);
$moment = date("Y-m-d h:i:sa");
$kiesmodel = Safesql($_POST['model']);
// validation
$sql = "SELECT * FROM prijzen WHERE model = '$kiesmodel'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
if (count($row) >= 1) {
echo "<script>alert('You already add this model')</script>";
}else{
if(!$mysqli->query("INSERT INTO prijzen (prijs, created, model) VALUES (".$prijs.",'".$moment."' , '".$kiesmodel."')")) {echo $mysqli->error;}
else{ echo "het toevoegen is gelukt";}
Laden(0);
}
}
may it can help you

Display drowdown values after user has selected 3 option

I have 3 drop downs I want to display whatever the user will select after he/she has selected a function or a scrpt will do but it must be within the script
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
//Names dropdown:
echo '<select name="id" id="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="id" id="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="id" id="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo "<button id='write_in_div'>Click me!</button>";
echo '</form>';
}
?>
Something that will call the write_in_div When Click me! button is press or any other method that can be used to display 3 selection user selected
The Output should be something like You select 1) Name 2)Surname and Email
You have an error in your html selects each select has the same name "id" they each need to be unique so you can detect then.
You need to detect if the user has submitted the form
if(isset($_POST["select_name"])) {
echo $_POST["select_name"];
}
There is a big mistake on you form.
In a form, each select and input MUST have a unique name. You need this name to retrieve the submitted value back in your php script.
I suppose you have this:
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form method="post" action="test.php">';
//Names dropdown:
echo '<select name="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo '<button id="write_in_div">Click me!</button>';
echo '</form>';
}
When the form is submitted, test.php will have the posted data: $_REQUEST['names'], $_REQUEST['surnames'] and $_REQUEST['emails'].
You just have to check the content of thoses vars and print them if not null.
Note1: ?> is useless at the end of a file.
Note2: be carefull about ' and " when writing an html file. The value of an html attribute is written with ", not '.

Update Multiple Rows (PHP + MySQL)

I am working on a lead management system - and as the database for it grows the need for more bulk functions appears - and unfortunately I am getting stuck with one of them. The database stores many different leads - with each lead being assigned to a specific closer; thus the database stores for each lead the lead id, name, closer name, and other info. The main lead list shows a checkbox next to each lead which submits the lead id into an array:
<input type=\"checkbox\" name=\"multipleassign[]\" value=\"$id\" />
Now this all goes to the following page:
<?php
include_once"config.php";
$id = $_POST['multipleassign'];
$id_sql = implode(",", $id);
$list = "'". implode("', '", $id) ."'";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
?>
I want to be able to use the form on this page to select a closer from the database - and then assign that closer to each of the leads that have been selected. Here is where I have no idea how to continue.
Actually - i got it. I don't know why I didn't think of it sooner. First off I passed the original $list variable over to the new page - and then:
<?php
include_once"config.php";
$ids = $_POST['list'];
$closer = $_POST['closer'];
$query = "UPDATE `promises` SET `closer` = '$closer' WHERE id IN ($ids) ";
mysql_query($query) or die ('Error updating closers' . mysql_error());
echo "A new closer ($closer) was assigned to the following accounts:";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$businessname = mysql_result($result,$i,"business_name");
echo "<li>$businessname";
++$i; } } else { echo "The database is empty"; };
?>
The updated page before this:
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<form name=\"form1\" method=\"post\" action=\"multiple_assign2.php\">";
echo "<input type=\"hidden\" name=\"list\" value=\"$list\" />";
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
echo "<input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Reassign Selected Leads\">";
?>
After you select the leads and submit the form , your script should show them in a list with hidden inputs (with name=leads[] and value=the_lead's_id) and next to each lead there will be a dropdown box () which will be populated with all the closers.
After choosing and sending the second form your script will "run" all-over the leads' ids array and update each and every one of them.
Got the idea or you want some code?

Why are two entries of $_POST undefined when accessed in my code while the rest are fine?

I am working on PHP and databases for an assignment and I would like some help on my coding. The form is submitted to process.php for processing (code for both are reproduced below). I am getting an undefined index warning for $_POST['CustomerID'] and $_POST['BodyStyle'] when process.php runs (the exact location is noted in the code), and the information entered for these fields on the form won't get inserted or updated in the database. The other fields work as intended, generating no errors and are stored in the database. What is going wrong? How can I fix it?
Process.php:
<?php
$dbname = "cars";
$dbuser = "carsuser";
$dbpass = "carspass250";
$dbconnect = odbc_connect($dbname,$dbuser, $dbpass)
or die ("Could not connect. <br>");
$opcode = (int) $_POST["opcode"];
$recno = (int) $_POST["recno"];
if ( ($opcode < -1) || ($opcode > 1) )
{
echo "Invalid data passed from form! <br>";
exit();
}
if (($opcode == 0) || ($opcode == 1))
{
$CustomerID = $_POST['CustomerID']; //Undefined Index
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$BodyStyle = $_POST['BodyStyle']; //Undefined Index
$color = $_POST['color'];
if (!all_fields_ok($CustomerID, $year, $make, $model, $BodyStyle, $color))
{
exit();
}
}
if ($opcode == -1)
$SqlStatement = "DELETE from Vehicle WHERE VehicleID = $recno";
if ($opcode == 0)
{
$SqlStatement = "UPDATE Vehicle SET ".
"CustomerID = '$CustomerID', ".
"Year = '$year', ".
"Make = '$make', ".
"Model = '$model', ".
"BodyStyle = '$BodyStyle', ".
"Color = '$color' ".
"WHERE VehicleID = $recno";
}
if ($opcode == 1)
{
$SqlStatement = "INSERT INTO Vehicle ".
"(CustomerID, Year, Make, Model, BodyStyle, Color) ".
"VALUES ('$CustomerID', '$year', '$make', '$model', '$BodyStyle', '$color')";
}
print $SqlStatement."<br>";
$recs = odbc_exec($dbconnect, $SqlStatement)
or die ("Could not locate database");
print "Database Updated! <br>";
print "<a href=listall.php>Return to List</a> ";
function all_fields_ok($CustomerID, $year, $make, $model, $BodyStyle, $color )
{
$errormsg = "";
$flag = 0;
if ( (!is_numeric($CustomerID)) )
{
$errormsg = $errormsg."Input: $CustomerID <br>";
$errormsg = $errormsg."Only numbers are aloud <br><br>";
$flag=1;
}
if(!(is_numeric($year)) || (!(strlen($year)==4)))
{
$errormsg = $errormsg."Input: $year <br>";
$errormsg = $errormsg."Please enter a four-digit year <br><br>";
$flag=1;
}
if ((!ctype_alpha($make)) )
{
$errormsg = $errormsg."Input: $make <br>";
$errormsg = $errormsg."Please enter the make of the vehicle, characters only<br> <br>";
$flag=1;
}
if (!(ctype_alnum($model)) )
{
$errormsg = $errormsg."Input: $model<br>";
$errormsg = $errormsg."Please enter the model of the vehicle, numbers and characters aloud <br><br>";
$flag=1;
}
if ((!ctype_alpha($BodyStyle)) )
{
$errormsg = $errormsg."Input: $BodyStyle <br>";
$errormsg = $errormsg."Please enter the bodystyle of the vehicle, characters only <br><br>";
$flag=1;
}
if ((!ctype_alpha($color)) )
{
$errormsg = $errormsg."Input: $color <br>";
$errormsg = $errormsg."Please enter the color of the vehicle, characters only. <br><br>";
$flag=1;
}
if ($flag == 1)
{
echo "Data not trustworthy. Please revise input and try again. <br><br>";
echo $errormsg;
return false;
}
else
return true;
}
?>
form:
<?php
$dbname = "cars";
$dbuser = "carsuser";
$dbpass="carspass250";
$dbconnect = odbc_connect($dbname,$dbuser, $dbpass)
or die ("Could not connect. <br>");
$opcode = (int) $_POST["opcode"];
$recno = (int) $_POST["recno"];
if ( ($opcode < -1) || ($opcode > 1) )
{
echo "Invalid data passed from form! <br>";
exit();
}
if ($opcode == 0)
{
$SqlStatement = "SELECT * from Vehicle WHERE VehicleID = $recno";
$recs = odbc_exec($dbconnect, $SqlStatement)
or die ("Could not execute query");
$row = odbc_fetch_array($recs) ;
$VehicleID = $row['VehicleID'];
$CustomerID = $row['CustomerID'];
$year = $row['Year'];
$make = $row['Make'];
$model = $row['Model'];
$BodyStyle = $row['BodyStyle'];
$color = $row['Color'];
}
else
{
$recno = 0;
$VehicleID = 0;
$CustomerID = "";
$year = "";
$make = "";
$model = "";
$BodyStyle = "";
$color = "";
}
print "<h1>Vehicle Record </h1>";
print "<form action=process.php method=post> \n";
print "<table>";
if ($opcode == 0)
print "<tr><td> Record Number:</td><td align=left>$recno</td> </tr>\n";
else
print "<tr><td> Record Number: </td><td align=left>New Record</td> </tr>\n";
print "<tr><td> Customer ID: </td>";
print "<td> <input type=text name=CustomerID value=\"$CustomerID\"></td></tr> \n";
print "<tr><td> Year: </td>";
print "<td> <input type=text name=year value=\"$year\"></td></tr> \n";
print "<tr><td> Make: </td>";
print "<td> <input type=text name=make value=\"$make\"></td></tr> \n";
print "<tr><td> Model: </td>";
print "<td> <input type=text name=model value=\"$model\"></td></tr> \n";
print "<tr><td> Style: </td>";
print "<td> <input type=text name=BodyStyle value=\"$BodyStyle\"></td></tr> \n";
print "<tr><td> Color: </td>";
print "<td> <input type=text name=color value=\"$color\"></td></tr> \n";
print "<input type=hidden name=opcode value=$opcode> \n";
print "<input type=hidden name=recno value=$recno> \n";
print "<tr><td> <input type=submit value='Submit Record'></td><td></td></tr> \n \n";
print "</table>";
print "</form>";
odbc_close($dbconnect);
?>
The variables in your $_POST data are defined by the input name attributes, so if you say this
<input name="customer" ... />
<input name="style" ... />
you need to look for
$_POST['customer']
$_POST['style']
so either change your POST lookups or your input names, and make them match.
Also, you should check your html standards, the attributes values should go between "" and you should close all tags with either or finishing it with />
you're not getting the CustomerID and the BodyStyle variables from your POST data, there's something wrong with the request (your form, or whatever you're using)
Correct this column...it cannot have space in it.
"Body Style = '$BodyStyle', ".

Categories