Saving checkboxes in Session PHP - php

i need your help.
I'm trying to save the checkbox values in a session and show, on a second php file.
But the Session is in the second php file always NULL.
If i output the Session and the Post on the one.php, the array looks fine.
one.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<h1>Show checkboxes:</h1>
<form action="two.php" method="post">
<input type="checkbox" name="vehicle[]" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle[]" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle[]" value="Boat" checked> I have a boat<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$_SESSION['test'] = $_POST['vehicle'];
var_dump($_POST['vehicle']);
echo "</br>";
var_dump($_SESSION['test']);
?>
two.php
<?php
session_start();
$arr = $_SESSION['test'];
var_dump($arr);
foreach($arr as $value)
{
echo $value;
echo "</br>";
}
?>

Related

how to send database records one by one to another page in php

i am creating a quiz system same like http://www.sqlquiz.com/ and i have problem in the result page.
i have created 4 pages
index.php ---->welcomePage where i use a varible n in query string
index.php
<p>Start SQL Quiz</p>
2.quizmain.php------------>this page shows questions and their options and after
getting responce for each question it will go to the process.php page where the score is calculate and every time the counter is incremented by 1 so that after reaching 10th question the final result page will be displayed
quizmain.php
<?php
session_start();
require_once("connection.php");
extract($_REQUEST);
$number = (int) $_GET['n']; //starting value 1
echo $number;
$n1=rand(1,100);
$_SESSION['RQuestionNumber']=$n1;
$q=mysql_query("select * from quiz WHERE qno = '".$n1."'");
$a=mysql_fetch_array($q);
echo $a['qno'];
echo $a['ans'];
?>
<body>
<table>
<tr>
<td width="757" height="390"><div align="center">
<form method="post" action="process1.php">
<input type="radio" name="question" value="a" />
<?php echo $a[2]?></label>
</p>
<p><br />
<label>
<input type="radio" name="question" value="b" />
<?php echo $a[3]?></label>
</p>
<p><br />
<label>
<input type="radio" name="question" value="c" />
<?php echo $a[4]?></label>
</p>
<p><br />
<label> </label>
<label>
<input type="radio" name="question" value="d" />
<?php echo $a[5]?></label>
</p>
<p> </p>
<p>
<label>
<input type="submit" value="Submit" name="Submit" />
<input type="hidden" name="number" value="<?php echo $number; ?>" />
</form>
</label>
<br />
<br />
<br />
</p></td>
</tr>
</table>
</body>
</html>
process.php
<?php
session_start();
require_once('connection.php');
extract($_REQUEST);
//Check to see if score is set_error_handler
if(!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
}
if($_POST)
{
$number = $_REQUEST['number']; //value of number is 1 initially
$selected_choice = $_REQUEST['question'];
$next = $number+1; //
$total=10;
$_SESSION['RQuestionNumber'];
$q = mysql_query("SELECT ans FROM quiz WHERE qno = '".$_SESSION['RQuestionNumber']."'");
$result=mysql_fetch_array($q);
//$store=array();
//Compare
if($result[0][0] == $selected_choice){
//Answer is correct
$_SESSION['score']++;
}
//Check if last question
if($number == $total){
header("location: resultTable.php");
exit();
} else {
header("location: quizmain.php?n=".$next); //now the value of n is 2
}
}
?>
resultTable.php
now in this page i want to print all the questions which appear during the quiz (Same set of questions) along with the marked answer and correct ans
i have tried using session variables but it don't work.
<?php session_start(); ?>
<p>Final Score: <?php echo $_SESSION['score']; ?></p>
<?php session_destroy(); ?>
You session value will be override each time so at last you will get last questtion id. If you want all question Ids then use array. Try this:
quizmain.php
<?php
session_start();
require_once("connection.php");
extract($_REQUEST);
$number = (int) $_GET['n']; //starting value 1
echo $number;
$n1=rand(1,100);
$_SESSION['RQuestionNumber'][]=$n1;
$q=mysql_query("select * from quiz WHERE qno = '".$n1."'");
$a=mysql_fetch_array($q);
echo $a['qno'];
echo $a['ans'];
?>
<body>
<table>
<tr>
<td width="757" height="390"><div align="center">
<form method="post" action="process1.php">
<input type="radio" name="question" value="a" />
<?php echo $a[2]?></label>
</p>
<p><br />
<label>
<input type="radio" name="question" value="b" />
<?php echo $a[3]?></label>
</p>
<p><br />
<label>
<input type="radio" name="question" value="c" />
<?php echo $a[4]?></label>
</p>
<p><br />
<label> </label>
<label>
<input type="radio" name="question" value="d" />
<?php echo $a[5]?></label>
</p>
<p> </p>
<p>
<label>
<input type="submit" value="Submit" name="Submit" />
<input type="hidden" name="number" value="<?php echo $number; ?>" />
</form>
</label>
<br />
<br />
<br />
</p></td>
</tr>
</table>
</body>
</html>
process.php
<?php
session_start();
require_once('connection.php');
extract($_REQUEST);
//Check to see if score is set_error_handler
if(!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
}
if($_POST)
{
$number = $_REQUEST['number']; //value of number is 1 initially
$selected_choice = $_REQUEST['question'];
$next = $number+1; //
$total=10;
$last_que = $_SESSION['RQuestionNumber'][count($_SESSION['RQuestionNumber'])-1];
// $_SESSION['RQuestionNumber'];
$q = mysql_query("SELECT ans FROM quiz WHERE qno = '".$last_que."'");
$result=mysql_fetch_array($q);
//$store=array();
//Compare
if($result[0][0] == $selected_choice){
//Answer is correct
$_SESSION['score']++;
}
//Check if last question
if($number == $total){
header("location: resultTable.php");
exit();
} else {
header("location: quizmain.php?n=".$next); //now the value of n is 2
}
}
?>
resultTable.php
<?php session_start(); ?>
<p>Final Score: <?php echo $_SESSION['score']; ?></p>
<?php
var_dump($_SESSION['RQuestionNumber']); //You will get all question number here
?>
<?php session_destroy(); ?>
You can store arrays on sessions, so every time you run process.php you can add an array with question number and given answer, that way at the resultTable.php you could just select the 10 questions from the db and compare with the given answers.
Add into process.php:
if(!isset($_SESSION['answers'])) {
$answers = new array();
} else {
$answers = $_SESSION['answers'];
}
$answers[] = array($_SESSION['RQuestionNumber'], $selected_choice);
$_SESSION['answers'] = $answers;
So what this code does is create an array to store question and user given answer and saves it in the session, this way you can loop this array on the resultTable and show all the question on the quiz.
PS: this is very basic code, there are a lot you need to do in order to use it on your quiz game, i.e. you should check if the array is not set from previous runs
You Can use Sessions for That
simple syntax of sessions is:
session_start();
$_SESSION['score'] = $data;
Now you can use your $data at another page by just starting session like this
session_start();
echo $_SESSION['score'];
To remove data you should destroy the session
session_destroy();

How can i pass arithmetic operation result after form submit?

This is my first php program. Im trying to compare the result of adding two randomly generated numbers (visually displayed before text field) to the answer i give in the submit. But it just wont work. I pass the result at $value3 and try to compare it to the result of the submit. Any ideas guys?
<head>
<title>
</title>
</head>
<?php
$displayForm=True;
if(isset($_GET['result'])){
$displayForm=False;
}
if($displayForm){
?>
<body>
<form method="GET">
result
<?php
$value1=rand(1,10);
$value2=rand(1,10);
$value3=$value1 + $value2;
echo($value1);
echo("+");
echo($value2);
?>
<input type="text" name="number">
<input type="hidden" name="val3" value="$value3">
<input type="submit" name="result" value="submit">
</form>
<?php
}
if(isset($_GET['result'])){
if(isset($_GET['result'])){
$result = $_GET['result'];
}
if($result==$_GET['val3']){
echo "result right: you re human";
}
else{
echo "lol you are a retarded cat";
}
}
?>
</body>
Try this
<body>
<form method="GET">
result
<?php
$value1=rand(1,10);
$value2=rand(1,10);
$value3=$value1 + $value2;
echo($value1);
echo("+");
echo($value2);
?>
<input type="text" name="number">
<input type="hidden" name="val3" value="<?php echo $value3; ?>">
<input type="submit" name="result" value="submit">
</form>
<?php
}
if(isset($_GET['result'])){
if(isset($_GET['result'])){
$result = $_GET['number'];
}
if($result==$_GET['val3']){
echo "result right: you re human";
}
else{
echo "lol you are a retarded cat";
}
}
?>
</body>

Stack array losing previous values for single page submission

I'm trying to do the push-and-pop stack array in PHP but only the last value is stored. How can I store the other values as well even if I click on the button again & load the same page?
This is what I've done:
<?php
if(!$_GET)
$myStack = array();
else
$myStack[] = "";
?>
<html>
<head> <title>Exercise</title>
</head>
<body>
<form action="test.php" method="get">
Element: <input type="text" name="num" value="0"/><br/>
<input type="submit" name="push" value="push" />
<input type="submit" name="pop" value="pop" />
</form>
<?php
if(isset($_GET["push"])){
array_push($myStack, $_GET["num"]);
foreach($myStack as $val)
echo $val . " ";
}
elseif(isset($_GET["pop"])){
array_pop($myStack);
foreach($myStack as $val)
echo $val . " ";
}
?>
</body>
</html>
Every http request php will execute script with all variables from scratch. You have to use $_SESSION or static variables to save values between requests. To store array in $_SESSION just assign it to key:
$_SESSION["myStack"] = array();
$_SESSION["myStack"][] = 1;
$_SESSION["myStack"][] = 2;
You have a reset at the top off your script. After reload your stack will be empty. Also you have to save your stack into a session var.
Here's the code with using a session to store the array:
<?php
//starts the session
session_start();
$myStack = array();
//gets the array from the session if it exists
if (isset($_SESSION['stack']))
$myStack = $_SESSION['stack'];
?>
<html>
<head> <title>Exercise</title>
</head>
<body>
<form action="test.php" method="get">
Element: <input type="text" name="num" value="0"/><br/>
<input type="submit" name="push" value="push" />
<input type="submit" name="pop" value="pop" />
</form>
<?php
if(isset($_GET["push"])){
array_push($myStack, $_GET["num"]);
foreach($myStack as $val)
echo $val . " ";
}
elseif(isset($_GET["pop"])){
array_pop($myStack);
foreach($myStack as $val)
echo $val . " ";
}
//stores the array in the opened session
$_SESSION['stack'] = $myStack;
?>
</body>
</html>

when perfoming a multiple row updates, how do i access other form element values, apart from the checkbox?

i wrote a piece of code to do multiple row deletions based on ticked check boxes.
Now i need to mordify it to do multiple row updates.
i have been failing to access the textbox values for each row.
here's my code, in general.
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<input type="checkbox" <?php echo 'name="SaveEachComment['.$row["comment"].']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment" size="55" value="<?php echo $comment;?>" />
<input type="submit" name="SaveComments" value="submit" />
</form>
I just added a for loop to print multiple form fields. Obviously your iteration would be as many as number of rows, so you can change that part of the code. But try this:
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
echo $_POST['rowcomment'][$key] . "<br />\n";
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php for ($i=0; $i<11; $i++) { ?>
<input type="checkbox" <?php echo 'name="SaveEachComment['.$i.']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment[<? echo $i?>]" size="55" value="<?php echo $comment;?>" />
<br />
<?php } ?>
<input type="submit" name="SaveComments" value="submit" />
</form>

PHP Form Processing Order precedence

Am new to the world of development and am just starting to pick up PHP. I have basic form that attempts to validate the checkboxes the user has selected or checked. My code is below. The question I have is why is that when I have the order of my form as follows, the form does not pass the value NET, PHP or RUBY and the values that are costantly passed are no.
--- Form code that does not work ---
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="hidden" name="ch3" value="no">
<input type="submit" name="submit" value="submit">
However if my code is as follows;
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch3" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
The boxes appear checked. The entire code below.
<?php
$ch1status = "unchecked";
$ch2status = "unchecked";
$ch3status = "unchecked";
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
if($_POST["ch1"] == "net") {
$ch1status = "checked";
}
}
if(isset($_POST["ch2"])) {
if($_POST["ch2"] == "php") {
$ch2status = "checked";
}
}
if(isset($_POST["ch3"])) {
if($_POST["ch3"] == "ruby") {
$ch3status = "checked";
}
}
if ($_POST["ch1"] == "no" && $_POST["ch2"] == "no" && $_POST["ch3"] == "no") {
print "There is no such choice";
}
}
?>
<html>
<head>
<title>Sample form checkbxoes</title>
</head>
<body>
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch3" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
print $_POST["ch1"];
print $ch1status;
}
if(isset($_POST["ch2"])) {
print $_POST["ch2"];
print $ch2status;
}
if(isset($_POST["ch3"])) {
print $_POST["ch3"];
print $ch3status;
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
</body>
</html>
</form>
Also is there any other way of validating if the user has not selected any checkboxes as opposed to using hidden form fields.
Its just a browser-issue and its quite simple: The elements have the same name and the later element overwrites the first one.
Another way of validating, if a checkbox is not checked is to check, if its set in the $POST-array. If its missing, its treated like "not checked".
UNDEFINED INDEXES:
This is because checkboxes are only sent if they are checked. One thing you can do is always check the variable with isset (e.g. isset($_POST['ch1'])) before using them; another is to name your checkboxes the same thing with a [] following the name (e.g. name="languages[]") and then do something like this:
// Create a list of languages that are OK (remember, some users are malicious)
$languages = array('net','php','ruby');
// Compile a list of the answers the user picked; force it to be an
// array by either explicitly casting to an array, or using an empty array
// if none chosen
$picked = isset($_POST['languages']) ? (array)$_POST['languages'] : array();
// first, use array_intersect to remove entries present in one and not the other
// i.e. invalid entries from the client or entries not picked from the whole list
// then, "flip" the array so that the values become keys,
// because isset is faster than in_array
$valid_langs = array_flip(array_intersect($languages, $picked));
// check on languages
if (isset($valid_langs['php'])) { /* PHP picked */ }
if (isset($valid_langs['net'])) { /* NET picked */ }
if (isset($valid_langs['ruby'])) { /* Ruby picked */ }
Simpler Solution:
<form>
<input type="checkbox" name="php" value="yes" />
<input type="checkbox" name="net" value="yes" />
<input type="checkbox" name="ruby" value="yes" />
</form>
<?php
$php = $net = $ruby = 'unchecked';
if (!isset($_POST['php'],$_POST['net'],$_POST['ruby'])) {
echo 'There is no such choice';
}
else {
if (isset($_POST['php']) && $_POST['php'] == 'yes') {
$php = 'checked';
}
if (isset($_POST['net']) && $_POST['new'] == 'yes') {
$net = 'checked';
}
if (isset($_POST['ruby']) && $_POST['ruby'] == 'yes') {
$ruby = 'checked';
}
}
// ... snip ...
There are a great many ways to do this. Hopefully you will be interested in learning many of them.
Php is all server-side, so in order to keep them from submitting you'll need client-side validation. Easiest client-side validation is with javascript, or jQuery's Validation Plugin if you're already using jQuery (which you should be if you plan on using AJAX at any point).
And yes, you can get rid of those hidden inputs.
You do not need those hidden fields. Remove them and it should work.
EDIT:
Check out this modification
$ch1status = "unchecked";
$ch2status = "unchecked";
$ch3status = "unchecked";
if(isset($_POST["submit"])) {
if(#$_POST["ch1"] != "") {
$ch1status = "checked";
}
if(#$_POST["ch2"] != "") {
$ch2status = "checked";
}
if(#$_POST["ch3"] != "") {
$ch3status = "checked";
}
if (#$_POST["ch1"] . #$_POST["ch2"] . #$_POST["ch3"] == "") {
print "There is no such choice";
}
}
?>
<html>
<head>
<title>Sample form checkbxoes</title>
</head>
<body>
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="checkbox" name="ch1" value="net" <?php echo $ch1status; ?>>.NET
<input type="checkbox" name="ch2" value="php" <?php echo $ch2status; ?>>PHP
<input type="checkbox" name="ch3" value="ruby" <?php echo $ch3status; ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
print $_POST["ch1"];
print $ch1status;
}
if(isset($_POST["ch2"])) {
print $_POST["ch2"];
print $ch2status;
}
if(isset($_POST["ch3"])) {
print $_POST["ch3"];
print $ch3status;
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
</body>
</html>

Categories