How to use if & else to find an answer in an array? - php

I am having a problem with simple PHP app where a user has to enter a correct answer from a list of available options. And that options are stored in an array. The problem is that i cannot use the options anytime in the script other than the array declaration point. I might sound dumb...and i am, believe me. Lets say this is the array:
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
Now there is a text box in my script and $_POST method is used to submit the form. The correct choice which i have selected is 'Sports'. Now there are 4 possibilities a user might click submit, they are listed below.
A user clicks the submit button without entering any text in the textbox.
A user guesses the wrong choice which is from the $hobbyChoices but not 'Sports'.
A user guesses a choice which is not from the array. i.e anything other than what is in the array.
Finally, the user enters the correct choice that is 'Sports'.
This might seem pretty easy but the problem is that i cant use the names of the hobbies anywhere in the script, as mentioned before, other than the array declaration. Can i please get help? Also, when i tried to do one of the 4 possibilities, i encountered a problem with the uppercase and lowercase. This is seriously getting irritating, any help would be greatly appreciated.
Thanks!

If I am understanding your question correctly, the following is what you are looking for:
<?php
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
if (isset($_POST['answer'])) {
$answer = mysql_real_escape_string($_POST['answer']);
$correct_answer = $hobbyChoices[4];
$response = "Your answer is not one of the answers listed!";
foreach ($hobbyChoices as $value) {
if (strtolower($answer) == strtolower($value) && (strtolower($answer) != strtolower($correct_answer))) {
$response = "You selected the wrong answer from the list of options!";
}
else if (strtolower($answer) == strtolower($value) && (strtolower($answer) == strtolower($correct_answer))) {
$response = "You have answered correctly!";
}
}
print $response;
}
?>
<form name="form" method="post">
<table>
<tr>
<td>What is baseball?
</td>
<td><input type="text" name="answer" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
strtolower is a function in php that converts strings to lowercase and would help you compare your two values.

Related

How can we process a dynamic form in php

The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.

Php if Else in form action

Im trying to make an online concert ticket system and this is my problem..
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php $action; ?>" method="post">
And it doesn't work. Thank you in advance!
heres the full codes for the particular file that has a problem.
<html>
<head>
<title>Ariana Grande Concert</title>
</head>
<body>
<br>
<table>
<tr>
<td><img src="ariana2.jpg" height="300" width="260"></td>
<td></td><td></td><td></td>
<td>
<h2>ARIANA GRANDE THE HONEYMOON TOUR</h2><br>
<font face="Lucida Sans Unicode"> March 11, 2017<br>
Grand Ballroom, Solaire Resort & Casino<br>
Due to peoples demand, Ariana Grande is back in the Philippines<br>
Ariana Grande Live in the Philippines on <b> March 11, 2017!</b></font>
<br><br><br><br><br><br><br><br>
</td>
</tr>
</table>
<br><br>
<hr>
<br>
<center>
<table cellspacing="10" cellpadding="10" bgcolor="gray">
<tr>
<td><font face=""><b>TICKET PRICES:</b></font></td>
<td><b>VVIP:</b> <u>Php 25,000.00</u></td>
<td><b>VIP:</b> <u>Php 20,000.00</u></td>
<td><b>Upper Box A:</b> <u>Php 15,000.00</u></td>
<td><b>Upper Box B:</b> <u>Php 15,000.00</u></td>
<td><b>Lower Box A:</b> <u>Php 10,000.00</u></td>
<td><b>Lower Box B:</b> <u>Php 10,000.00</u></td>
<td><b>General Ad:</b> <u>Php 5,000.00</u></td>
</tr>
</table>
</center>
<br><br>
<font face="Lucida Sans Unicode" size="2"><b>Ticket Type: </b></font>
<?php
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
echo '<font face="Lucida Sans Unicode" size="2"><b> Quantity: </b></font>';
$Quantity = range (1, 30);
echo '<select name="Quantity">';
foreach ($Quantity as $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
?>
<form action="<?php echo $action; ?>" method="post">
<br><br><br>
<button class="btnExample" type="submit" value="Submit"/>Next</button>
<style>
.btnExample {
color: #0000;
background: white;
font-weight: bold;
border: 1px solid #0000;
border-radius: 10px 10px 10px;
}
</style>
</form>
</body>
</html>
Heres the full codes of the webpage that has a problem.
You did not echo the variable to show the output:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php echo $action; ?>" method="post">
Notice the <?php echo $action; ?>
Note: This is not the answer, and you should not accept this as answer, I am posting it here instead of posting in the comment section, because it's to long.
Note - You can solve your problem by your self, but for other it is impossible, as your code is just not making any sense at the moment, but I am pretty sure it will if you are able to read and understood what I am trying to say here in the solution.
First thing first,
Access Denied problem –
Note - you don’t have to fix this problem it will get fix by it self, but you should know why you have this problem, so in the future if you get the problem, you will know what to correct.
The reason it denying the access is this, that you are not allow to give special character for form action so after adding the echo in the form you are going to have this problem, because as soon as you add the echo in our form action you unknowingly giving special character to the action, because you never set the value for your variable $action so value for variable $action is equal to error message. So after adding the echo you are displaying that error message.
before doing any thing run your file in the browser and check the source code,
and see the value in the form action, it will be some thing like this
<br /><b>Notice</b>: Undefined variable: action in <b>C:\in here you are going to have file path\form.php</b> on line <b>1</b><br />
notice how many angle brackets colon you got in the here, you are not even allowed one angle brackets, so browser is thinking you are trying to do some thing malicious and that's why its blocking your access.
If you don’t know how to check source code, just type how to see source code and give your browser name (don’t ask me it just one click away)
so your code is basically generating error message and displaying it for the action after adding the echo and that's why browser is blocking the access
so why it was not doing the same thing before adding the echo, because in php, if you don’t use echo you are not displaying any thing, so before adding the echo, your action was empty, just remove the echo from the form action and check the source code again, you will understand what I am trying to say.
Again you don’t have to fix it, it will get fix by it self, remember this.
Now the solution start from here
First I have to be right about my assumption, that what you are trying to do,
So these are my assumption, what you want to do,
People should be able to buy different different types of ticket, and they can choose the number of ticket from 1 to 30,
Than you want to run different file according to the TicketType, in one case you want to run seat.php and in one case you want to run index.php,
And to achieve your goal, you created a form, use the if statement to set your action value in the form, as I can see you are using variable $action in the form for action, and you set this value through your if statement.
If I am wrong about any thing up until now, don’t read further it will be waste of time.
basically to achieve your goal, you are using form, array and some logic,
in your case you seems to know array and logic, but you lack pre basic knowledge about the form, and that's why your code is not working.
To be honest. In my opinion you know nothing about the form. That's why it is impossible to give you solution(at least for me). But I am quite sure, if you read this fully you will be able to solve your problem by your self,
so give a quick read to the points, and you will be surprised how easy it is to solve your problem for you, and you will also realized why it is impossible for other to solve it for you, at the moment.
Now Start from here
I am dividing the problem in Four part
Some important Notes about the form.
$Ticket_Type is not equal $TicketType - an you can not even use $TiccketType here
Select option only passes the value from the value tag-- Two part solution
Your logic is at the wrong place,
1. Some important point about the form.
When you use form, you have to tell php, that you are submitting the form, and if you want to do it only with php, you have to use submit button for it(I already mention this in my comment other day),
second you need to know, what happened when you click on the submit button in the form, form will run the action file and also will pass the data from. opening form tag <form> to closing form tag </form> to that file
but any data which is out of these opening and closing form tag, form will not pass that data, so point is it only passes the data which is inside the opening form and closing form tag.
Look at the code below to understand it better, and please also run this code, so you can understand it better,
Few points about the code
in the below code, we have two input field location and name, location input field is out of the form tag and name input field is inside the form tag.
and our form action is seat.php, and name for form file is form.php for this example.
as our action is seat.php, so if you click on the submit button, it will pass the data to seat.php, and will run that file.
in seat php, we are just using echo to display both value,
see the code below for form.php and for seat.php,
form.php
Location<input type="text" name="location"/><br><br>//out side of the form tag
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$name = $_POST['name'];
echo $name.'<br>';
$location = $_POST['location'];
echo $location;
Now go and run form.php and type some thing in the location and name box, and click on the submit button, and if you do that, it will only display you the value for name but for location value it will display you the undefined index location error.
And the reason is, because your form never passed that value for location to seat.php1, becauselocationis out ofform` opening and closing tag,
Now put this Location field inside the form tag
now put that location inside the opening and closing form tag,
after doing that our code should look like this
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>//Now location is inside of the form
<input type="submit" value="Hot Air">
</form>
Now again run your form.php type some thing for name and for location and click on submit button, this time it will display you both the value, as this time both values are inside the form tag so both value get passed.
Note – If you can understand the difference between the first result and second result, you will be able to understand, why you need to have your select tag inside the opening and closing form tag, you can not have them out side of,
$Ticket_Type is not equal to $TicketType – and you can not even use $TicketType in here as it is equal to array you want value from the select option
For Second mistake, pay attention to this portion of your code
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
in here if you read this line echo ' <select name="Ticket_Type">' you give name for select Ticket_Type and than in the if statement You use the variable $TicketType, I am assuming you are checking the value for $TicketType, This problem you can solve it by changing the variable name $TicketType to $Ticket_Type In the if statement.
you have to correct this as well at the same place
So even after apply the above fix, your code wont work, cause you have second problem in this code
Now comes to the second problem, which you made in your if statement , in your if statement in here you checking $TicketType value, but you don’t have value for variable $TicketType because when you use the form php don’t set the variable it set the index so first you have to set the value for $TicketType than only you can use the if statement,
After applying both fixes your code should look like this
Note – (I am changing the name for select to TicketType )
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
$Ticket_Type = $_POST['Ticket_Type']; // Now you set the value for variable
// as your value is set, now you can type your if statement below.
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
3. Select option, pass value only from the value tag
Third mistake you make and this one you will not notice with this code, but if you don’t learn, you will likely to make that mistake in the future, so correct this mistake as well,
Just pay attention to this code
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
In here you have array, and than you are creating select option from your array which is fine, but you are making one fundamental mistakes in here, form will only passes the value form the value tag
so come to this line in your code
echo "<option value=\"$key\">$value</option>";
now change variable to $key to variable $value as well, because when you click on the submit button, again form only passes the value from value.
echo "<option value=\"$key\">$value</option>"; to echo "<option value=\"$value\">$value</option>";
it wont change the out come, for this code, as in your array key and values are same, but you should know what value you are passing for the future.
To Understand what I am trying to say here, run these two code from below, you will understand what I am trying to say.
form.php
<form action="seat.php" method="post">
<select name="Ticket_Type">
<option value="key1">First</option>
<option value="key2">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$value = $_POST['Ticket_Type'];
echo $value;
run this file in the browser and than select the option, and click on the submit button, it will display you key1 or key2 depending on the option you choose, not the first or second, as form only submit the value from value tag
now change value tag value to One and two, and run your code again,
<form action="seat.php" method="post">
<select name="Ticket_Type">;
<option value="One">First</option>
<option value="Two">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
Now again run the file in the browser, and chose the option and click on the submit, and see the outcome, and try to understand what is happening.
4 Your logic is at the wrong place
see this code
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
What your are trying to do here, in your head it make sense, that you will run the different different file,
according the ticket type, but in reality it does not make any sense, because when you click on the submit button, than only form will pass the value, to the action file,
this one is hard to explain
ok listen you have this variable $TicketType in this code, it only get set after you click on the submit button, and the action file it never going get set in this files, so you can not have these lines in this file. (and that's why it was showing to access forbidden after adding the echo)
Ok let's say you move this line to the different file, but still what you are trying to do with these lines is still silly, just don’t use these silly lines, and don’t try to run different different file, run single file, means give single action, and lets say action in the form is book.php
so our file name is book.php,
so starting shell for your book.php should look like this
if(!empty($_POST['Ticket_Type'])){
// what you are basically saying that if TicketType is not empty run this code,
// if it is empty run the else statement so the user will know that he did not select any ticket,
//now we are going to add some more code In here
}else 'Hey you did not select any ticket';
After adding the code in the middle our code will look like this
if(!empty($_POST['Ticket_Type'])){
$Ticket_Type = $_POST['Ticket_Type']; // set the value
if($Ticket_Type == 'VIP'){ //
// Copy and paste the index.php file code here
}else if ($Ticket_Type == 'VVIP') {
//copy and paste the seat.php file code here
echo $action;
}// if you have another Ticket_Type just add another else if here,
//Note: you can add as many else if you like,
}else 'Hey you did not select any ticket';
so just run single file action
i am still alive, after typing all this, if you have any confusion let me know.
Your Proble is here:
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
And your condition for if statment is
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
$TicketType is an array and you can't check it with a string, so your $action variable is not setting. and you have to provide index to check.
I had a similar problem where my error read "Object not found!
The requested URL was not found on this server. The link on the referr..."
Going off of aria_suhail_123's answer, you simply need to remove any php code surrounding your $action variable in your html like so:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= $action method="post">
The reason why is explained by aria_suhail_123, but since his/her response is very long... maybe this will help someone else!
Consider this :
<?php
if(!empty($_POST['tickettype'])){
if($tickettype == "VIP"){
?>
<script type="text/javascript">
window.location = "./seats.php";
</script>
<?php
}else if ($tickettype == "VVIP") {
?>
<script type="text/javascript">
window.location = "./seats1.php";
</script>
<?php
}
}else 'Hey you did not select any ticket';
?>

Form validation with a php array

I'm hoping someone could help me finish off some php code (the avon guy already kindly helped me with this but I'm still struggling with the last bit).
All it is, is I have a form where I have 10 particular sequences of digits, which if entered, allows the form to redirect to the following page. If anything else is entered I want the page to deny access with some kind of error prompt.
At top of the php, in the part before any php is printed, avon guy suggested an array to check the 10 correct sequences against.
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) != false) {
//match code in here
} else {
// fail code in here
}
I'm not sure what to put in the //match code in here AND the //fail code in here, bits. Can someone help me with this last bit please?
Many thanks
Jon
If you are just trying to redirect to another page using php, you can use header('Location: mypage.php');. More information on header here.
So for your code example (edited based on comment):
invitation.php
<?php
//invitation.php
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) === false)
{
//If fail
header('Location: formpage.php?errorMessage=Incorrect code!');
exit();
}
//If success:
//All of the invitation.php html and success code below
formpage.php
<?php
//formpage.php
if(!empty($_GET['errorMessage'])){
echo '<span>' . $_GET['errorMessage'] . '</span>';
}
?>
<form action="invitation.php" method="post">
<input name="rsvp" type="text" />
<input type="submit" value="Submit" name="submit" />
</form>

PHP Trivia Game using sessions

I am creating a trivia game, how it works:
A person goes to the index page.
The system generates him a random question out of the array.
The user answers the questions
If question is right, system will echo 'Correct answer' and will generate a new question.
If question is not equal to answer in the array, system will echo 'Wrong answer' and will generate a new question.
I have done the part of question generations, but I am having problems with the matching answers - Considering if you answer a question, after you click submit, the question automatically changes so your answer will be incorrect unless the randomQuestion stays the same.
My friend told me I need to use sessions for the random questions part, but nothing else.
I am not really sure how would I do this, I am really lost.
This is my code:
Question generation
<?php
session_start();
$questions = array(array('What is Google?', 'god'),
array('What is God?', 'gode'),
array('Why is god?', 'godee'));
$randomQuestion = array_rand($questions);
$question1 = $questions[0][0];
$question2 = $questions[1][0];
$question3 = $questions[2][0];
if ($randomQuestion == 0 && !isset($_SESSION['question1'])) {
echo $question1;
} else if ($randomQuestion == 1 && !isset($_SESSION['question2'])) {
echo $question2;
} else if ($randomQuestion == 2 && !isset($_SESSION['question3'])) {
echo $question3;
}
?>
Form + matching answers
This script is currently only checking for question 1 as a test.
<form action="index.php" method="post">
<input type="text" name="answer">
<input type="submit" value="Answer it!">
</form>
<?php
$answer = $_POST['answer'];
if (!empty($answer)) {
if ($randomQuestion == 0) {
if ($answer == $questions[0][1]) {
echo 'Correct Answer!';
unset($_SESSION['question1']);
unset($_SESSION['question2']);
unset($_SESSION['question3']);
}
} else {
echo 'Answer is incorrect.';
return;
}
} else {
echo 'Field is empty';
return;
}
session_destroy();
?>
What I have thought of:
After reading much articles about sessions, I thought about checking if randomQuestion is isset, if it's isset, then it won't generate new questions.
After you answer the question, it will unset the random question so the system can generate a new question.
But it didn't really work as I didn't do it right.
What did I do wrong?
And what is the easiest way to do this?
Thanks!
I wouldn't start by using sessions. Of course I may end up using them but for a proof of concept it's best to do it the simple way first.
All you really need to do is insert a hidden value into your form that will tell you the question number.
For example (not tested):
<?php
$questions = array(
array('What is Google?', 'god'),
array('What is God?', 'gode'),
array('Why is god?', 'godee')
);
$rnd=mt_rand(0,count($questions)-1);
$question=$questions[$rnd];
echo($question[0]);
?>
<form action="index.php" method="post">
<input type="hidden" name="q" value="<?=$rnd?>">
<input type="text" name="answer">
<input type="submit" value="Answer it!">
</form>
The rest of the server code to verify the question and answer I'll leave as an exercise.
If you want this trivia game to be played by more that one person (and I suppose you do) , you need to come up with something more that a simple < form > ... You must store the answers one user gives so that the other user can see them.

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Categories