PHP - Form question population based on user answer - php

So I'm trying to create a fuel calculator form using PHP and HTML. For the most part, I have the form pretty fleshed out, however, I'm stuck on one thing.
So I would like to create a fuel perks option that gets input from the user. The question that I wanted to pose to the user is whether or not they purchased groceries. If the user types yes, then I wanted a different input box to appear asking the user for the amount in groceries that they spent and then calculate the fuel points based on that input. However, I can't figure out how to get the initial question of how much did they spend on groceries to appear based on their answer.
Here is what I have so far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
How many miles did you drive? <input type="text" name="milesDriven" value="<?php echo $milesDriven;?>">
<span class="error">* <?php echo $milesDrivenErr;?></span>
<br><br>
What is your cars miles per gallon?:
<input type="text" name="milesPerGallon" value="<?php echo $milesPerGallon;?>">
<span class="error">* <?php echo $milesPerGallonErr;?></span>
<br><br>
Type of gas used:
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="87 octane - 1.89$/gal") echo "checked";?> value="1.89">87 octane - 1.89$/global
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="89 octane - 1.99$/gal") echo "checked";?> value="1.99">89 octane - 1.99$/global
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="92 octane - 2.09$/gal") echo "checked";?> value="2.09">92 octane - 2.09$/global
<br><br>
<input type="text" name="groceries"
<?php
if ($groceries = "yes") {
//code here that causes the input field to appear
}else if ($groceries = "no") {
//do nothing and proceed with the calculation
}
?>
<input type="submit" name="submit" value="Submit">
</form>
Can you create form inputs inside of a PHP block? Please forgive me if this is a dumb question. I'm still a beginner who's trying to learn more about backend coding.

Create a select tag inside the if block of yes and then calculate the amount the user has spend to purchase the groceries.

Can you create form inputs inside of a PHP block ? yes of course, you can just simply doing it like this
<?php
if ($groceries == "yes") {
echo "<input type='text' name='purchasedGroceries' value='".$purchasedGroceries."'">
}
?>
and calculate the fuel points when $groceries == "yes"

Related

Numbers inputted always reset in php

** Here are the Codes that i use**
** I use this for recording of the scores, there 5 zeros cause there are more 3 students
$Students_C1= array(0,0,0,0,0);
$Students_C2= array(0,0,0,0,0);
** These are for inputting numbers
<td>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" id="inputs" name="SampleUP" value="<?php $Students_C1[0]; ?>" placeholder="<?php echo $Students_C1[0] ?>">
<input type="hidden" name="UpdateC1" >
</form>
</td>
<td>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" id="inputs" name="SampleUPs" value="<?php $Students_C2[0]; ?>" placeholder="<?php echo $Students_C1[1] ?>">
<input type="hidden" name="UpdateC2" >
</form>
** And these are for updating the php array after i input those numbers
<?php
if( isset($_GET['UpdateC1']) )
{
$val1 = htmlentities($_GET['SampleUP']);
$Students_C1[0]=$val1;
}
else{}
if( isset($_GET['UpdateC2']) )
{
$val2 = htmlentities($_GET['SampleUPs']);
$Students_C2[0]=$val2;
}
else{}
?>
The flow should be if i input a number in C1 and C2 next to the student's name. that number should stay as i input. The problems is that after i input C2 number (After C1), both of the numbers reset to zero, but the C1 works fine
Any Potential solution is heartly welcomed. A complete beginner in PHP
Student Grading System
Okay, I can't see your output but firstly both your input IDs are the same name. Then, you do not have an input type as submit instead it is hidden. So how do you submit your form then? If you do not submit it, then there is no value passing through the GET request. Your form does not have a method as well. Next is you're having two forms on one page so I'm guessing that if you have two forms then u need to enter one form and submit it first before submitting the other? I guess that's the reason why only one of it is updated. You should include your webpage output as well to make it easier to debug.

PHP, HTML code review

I am working on a project called online Test, where users can take the test. I have created a php code in the following format but its hard coded. Below is the code. If I click on C it will take me to c test and similarly c++
<center><h2><b>Select the test</b></h2>
<div class="test"><b>C</b></div><br>
<div class="test"><b>C++</b></div><br>
</center>
Now the question is I want to make this page has dynamic. To fetch all the course that are there in the database and if user selects a particular test, he should get the test for that particular subject.
<form action="promo.php" method="post">
<h2><center>
<td><select name="links" id="links" value=' ' ">
<?php
while($row=mysql_fetch_array($out))
{
echo "<option value=" .$row['course_id']." > ". $row['c_name']." </option>";
}
?>
</select>
<input type="Submit" value="Start" /></center>
</form>
This is what I have done, it displays all the courses in the drop down fetching from the database. When I click the start button, it does not start any test because promo.php requires another parameter.
I am not able to send the course name along with the promo.php. How to do this
Can any one help me with this code
As some points is not cleared but I assume you can do like this :
Change select box name to name="course"
<select name="course" id="course">
And if you want to send a select box value to a page like this : promo.php?course=c then you should do method = "get" :
<form action="promo.php" method="get">
<h2><center>
<select name="course" id="course">
<?php
while($row=mysql_fetch_array($out))
{
echo '<option value="'.$row['c_name'].'" > '.$row['c_name'].' </option>';
}
?>
</select>
<input type="Submit" value="Start" /></center>
</form>
Perhaps I misunderstood the question, but why not include the other parameter in your form? Just add another <input type="text">, <select> or <input type="hidden">, as appropriate.

MySQLi/PHP - How can I display total "number" of users that chose one side vs the other?

This is as detailed as possible.
I have 2 forms used for pre-registration for an upcoming game. Depending on which form someone fills out, will depend on the side they are registering for. Regardless both forms insert data into the same table and everything is working great for that part.
The issue Im running into is when I try to display the count for the number of times a certain side (red or blue) is used in the database, nothing is displayed.
The end result should show something like "3 vs 2" on the page so people can see it and have it update automatically when new info is submitted.
Where 3 is the current total of times the "blue" side has been chosen and 2 is the current total of times the "red" side has been chosen.
The table name is "game_checkin" and the column for the sides is "side". The two possible answers are "red" or "blue". Both are hidden fields.
Both of my forms looks like this:
<form action="/pre-reg.php" method="post">
<input type="text" name="name" placeholder="Name" required><br/>
<input type="text" name="age" placeholder="Age" maxlength="2" required><br/>
<input type="text" name="location" placeholder="City, ST" required><br/>
<input type="text" name="callsign" placeholder="Callsign" maxlength="12" required>
<input type="hidden" name="date" value="<?php echo date ('m-d-Y');?>">
<input type="hidden" name="side" value="blue"> red has a value of "red"...
<input type="submit" value="Check In">
</form>
This is the current code I use. I supplied an open area for anyone wanting to tell me what I'm missing.
<?php
$con=mysqli_connect("localhost","user","password","dbname");
// Verify Connection - duh!
if (mysqli_connect_errno())
{
echo "You kicked my doge and now he no pee straight:<br/>"
. mysqli_connect_error();
}
///// SCHOOL ME HERE \\\\\
mysqli_close($con);
?>
Like I mentioned,
I need to know how to display the total "number" of users that chose "blue" vs "red".
Then echo it to the page, for example like: 3 vs 2
my resources: mysql 5, php 5, phpmyadmin, linux os, paid hosting...
I have been stuck on this for the past few days trying to find an answer everywhere I could look. If you can help, it will be greatly appreciated.
It's actually kinda trivial...
$sql = mysqli_query($con,"select `side`, count(*) from `game_checkin` group by `side`");
$sides = array("blue"=>0,"red"=>0);
while($row = mysqli_fetch_row($sql)) $sides[$row[0]] = $row[1];
echo $sides['blue']." vs ".$sides['red'];

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.

Problem with MySQL update [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
table updates empty spaces when user do not enter anything to the textbox
greetings :)
i am having problems updating my database whenever the user clicks on the submit button.
i am going to show you the flow of my program,i already tried figuring out the problem,but i just can't find solutions. i hope someone could help me.
i have 2 problems encountered here:
my database won't update after clicking the submit button
the user may choose which to update,if the textbox is empty,it will update the data with empty spaces.and i want the data to remain as it is if the textbox is empty.
in my program,if you want to update the employee information,you must click the name that contains a link in the page. (in my program its the employee name that needs to be clicked) when clicked,a pop up will open.
the link in my index.php contains the following code:
<td class="sub" width="100" align="center">
<a href="" onclick = javascript:newPopup('empinfo.php?emp=<?php echo $eid ?>');><?php echo$ename?></a>
</td>
NOTE the empinfo.php is my pop up window,it calls the pop up when clicked. emp isthe name i assign to pass in the empinfo.php it contains the employee ID. NO PROBLEM HERE,I JUST WANT TO SHOW YOU THE FLOW
when the empinfo.php appears,it will show this format:
Employee name: //textbox here
Position: /textbox here
Department: /textbox here
Employee Tag: /textbox here
**SUBMIT BUTTON**
when the user clicks the submit button, it should have updated the database with the inputted values,but mine won't update :(
here is the codes i used:
<?php
$con=mysql_connect('localhost','root','mariel') or die(mysql_error());
mysql_select_db('intranet',$con);
if(isset($_POST['submitted']))
{
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['name']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_GET['emp']."' ";
mysql_query($qry) or die (mysql_error());
}
?>
this is the content code in my form,together with the submit that i used:
<form action="index.php" method="POST">
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='eid' id='eid' value= '<?php echo $_GET['emp']?>' />
<fieldset>
<div class='container'>
<label for='ename' >Employee name:</label><br/>
<input type='text' name='ename' id='ename' value='' maxlength="50" /><br/><br/>
</div>
<div class='container'>
<label for='pos' >Position:</label><br/>
<input type='text' name='pos' id='pos' value='' maxlength="50" /><br/><br/>
</div>
<div class='container'>
<label for='dep' >Department/Division:</label><br/>
<input type='text' name='dep' id='dep' value='' maxlength="100" /><br/><br/>
</div>
<div class='container'>
<label for='tag' >Employee Tag:</label><br/>
<select name="tag" id="tag">
<option value="Y">Yes</option>
<option value="N">No</option>
</select> <br/><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' onclick = "location.reload();window.close()"/>
</div>
</fieldset>
</form>
i hope someone could clear it up for me
MisaChan
It's not updating because you probably need to refer to $_POST['eid'] instead of $_GET['emp'] because you don't have it in index.php like index.php?emp=1. You already have that field so use that:
<input type='hidden' name='eid' id='eid' value= '<?php echo $_GET['emp']?>' />
Also you don't need to do this:
onclick = "location.reload();window.close()"
Type submit reloads the page by default.
Lastly, consider #Sam152's pointers :)
There could be a number of things wrong, but these points should help you debug your script.
Firstly you need to escape your post
variables to ensure things like
apostrophes don't mess up your query,
it's also a security vulnerability.
Secondly, make sure your form action is pointing to the PHP script. Maybe put a print statement at the top of the script to make sure PHP is actually receiving the data.
Then assign the value of the SQL query to a variable and print it out before you run it. You can then easily see what's being sent to the SQL server. Maybe run it in an SQL management tool my phpMyAdmin and observe any errors with it.
Hope this helps. Feel free to update your question with new information as it comes.

Categories