incrementing inside a php function - php

I was wondering if you can help me with my php function
I have created a quiz which uses radio buttons and a submit button. I want the function to check if a specific radio button is selected and if so add 1 onto the user score. however nothing is being added the function for this is
function Score()
{
if(isset($_POST['correctAnswer'] ))
{
$answer=$_POST['correctAnswer'];
$_SESSION['score']=$userScore+1;
}
else
{
$_SESSION['score']=$_SESSION['score'];
}
}
and the form in which it is submitted is
echo '<strong>'."$theQuestion".'</strong><br>';
?> <form name="correctAnswer" form method="post" action="quiz.php" onSubmit="Score()">
<?php
echo "$theAnswer1";?> <input type="radio" id="correct_answer" name="correctAnswer">
<?php
echo "<br>$theAnswer2"; ?> <input type="radio" id="wrong_answer1" name="wrongAnswer1">
<?php
echo "<br>$theAnswer3"; ?> <input type="radio" id="wrong_answer2" name="wrongAnswer2">
<?php
echo "<br>$theAnswer4"; ?> <input type="radio" id="wrong_answer3" name="wrongAnswer3">
<input type="hidden" name="score" value="userScore">
<br><input type="submit" value="Submit Answer">
</form>
Hope you can help

You have to pass the counter as an argument of the function like this
function Score($userScore){
//Do the rest
}

Looks like the $_SESSION['score'] is undefined
function Score() {
if (!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
if (isset($_POST['correctAnswer'])) {
$_SESSION['score']++;
}
}

Related

How to submit the same form multiple times on same page and also process them on that page in php

I am trying to display a form and process data on same page multiple times.
This is my code:
<?php
function display($q) {
$que=mysqli_fetch_row($q);
$_SESSION['qid']=$que[0];
ob_start ();
?>
<form method="post" action="">
<h3> <?php echo $que[0]." . ".$que[2]; ?> </h3>
<input type="radio" name="ans" value="<?php echo $que[3]; ?>"> <?php echo $que[3]; ?> <br/>
<input type="radio" name="ans" value="<?php echo $que[4]; ?>"> <?php echo $que[4]; ?> <br/>
<input type="submit" name="next" value="next" >
</form>
<?php
$_SESSION['qid']=$que[0];
echo $_SESSION['qid'];
if(isset($_POST['next'])) {
if(array_key_exists('next',$_POST)){
next_que();
}
}
}
function next_que() {
//some code
// calling display function
}
?>
When I run this code, the display and next_que functions are working properly the first time, but on the next call only the display function is called displaying the form, and clicking the button doesn't turn the isset($_POST['next']) condition to true.
How can I get this to work?
Yes, prevent the form from submit via prevent default in your javascript. Then you can call your javascript functions / code on any button click and use the data in the same page.

php checkbox array submit issue

I have a problem with checkbox array
this is my code
<?php
include('config.php');
if(isset($_POST['submit']))
{
for($x = 0;$x <= 5;$x++)
{
if(isset($_POST['check'][$x]))
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check[]' />Never Expired</div>");
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST">
<div id="text">
<input type="checkbox" name="check[]" />Never Expired<br>
</div>
<input type="button" id="add-file-field" name="add" value="Add input field" />
<input type="submit" value="Upload File" name="submit" id="submit" />
</form>
</body>
</html>
in here i make example i create 5 checkbox
Checkbox1
Checkbox2
Checkbox3
Checkbox4
Checkbox5
and when i check Checkbox3
the output result is
THERE IS A VALUE
EMPTY
EMPTY
EMPTY
EMPTY
I want the result is like this
EMPTY
EMPTY
THERE IS A VALUE
EMPTY
EMPTY
how to make it like that ? please help me
You need to add the key to the array
<input type="checkbox" name="check[0]" />
and
var num = 1;
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check["+num+"]' />Never Expired</div>");
num++;
});
Checkboxes that are not checked are not sent to the server by the browser, and hence are not in the $_POST['check'] array. This is why THERE IS A VALUE always comes first.
You can see this for a guide in the future...
http://www.html-form-guide.com/php-form/php-form-checkbox.html
Your problem is , you just check that is is set. You must check thier value..
Fix your html form like this
<input type="checkbox" name="check" value="1"> checkbox1</input>
"----do the same---------------------------"2""---------2------->"//do this until you get your five checkbox
Then on php
<?php
include('config.php');
if(isset($_POST['submit']))
{
for($x = 0;$x <= 5;$x++)
{
if($_POST['check']==strval($x))
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
?>
Hope it works
PS. If anyone see errors please edit it.
Hope this is work
add
<input type="checkbox" name="check[0]" />
then
edit this
var x = 1;
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check["+x+"]' />Never Expired</div>");
x++;
});
then simple php code
if(isset($_POST['submit']))
{
// $x = cout($_POST['check']);
for($x = 0;$x <= 5;$x++)
{
if(strlen($_POST['check'][$x])>1)
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
thanks

Post form values where Field Names are dynamically created from a loop?

I have a page that is created dynamically from the information that a user has submitted on a previous page. For example on page 1, the user inputs some department names. They can enter as many as they want. On page 2, multiple sections are created for each department that was entered on page one. Inside each of these sections are going to be forms, I currently have it set up so that the names of the forms are created using a variable $a. I need to know how to post these items once the submit button in each section is clicked. I have tried several different ways and nothing is working. I want it so that ONLY the items with the same $a value as the submit button's $a get posted.
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a;?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a;?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
<?php
echo "</div>";
}
?>
*EDIT I need everything to be in one form because the point of the page is to add up all of the values that will be inserted into each of the individual sections later. *
**EDIT 2 :
I figured it out using #dirt 's jquery suggestion.
HTML:
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
<div id=$a>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a ?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a ?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<button type="submit" name="areaSub" value="<?php echo $a ?>" />Add</button>
<?php
echo "</div></div>";
} ?>
jQuery:
<script>
$(document).ready(function() {
$('#<?php echo $a ?>').submit(function() {
.post("include/action.php")
});
});
</script>
PHP:
if(isset($_POST['areaSub'])) {
$areaval = intval($_POST['areaSub']);
$area = mysql_real_escape_string($_POST["dep_area".$areaval.""]);
list($area_id, $area_name) = explode(',', $area, 2);
$bdep = mysql_real_escape_string($_POST["bdep".$areaval.""]);
echo $areaval;
echo $area_name;
echo $bdep;
}
EDIT: If its a single form with multiple sections and you don't want to trim out unwanted form data after the POST then I think you must use jQuery to trim the form values prior to the post to the server, so see my jQuery portion below for a crued example of how you would go about only posting the data for the selected button.
Short answer would be to use the Name/Value attributes of the submit button and evaluate that once posted. Multiple buttons with the same name can have different values and the values don't have to be the labels.
Example:
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<?php
# _POST:
if (isset($_POST['submit']) && $_POST['submit'] == '1') {
echo 'Department 1';
}
if (isset($_POST['submit']) && $_POST['submit'] == '2') {
echo 'Department 2';
}
?>
You could also use jQuery to get all elements contained in a certain Div ID. Something like (this is rough idea):
<div id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
</div>
jQuery:
$('#<?php echo $a; ?>').submit(function() {
do_something_with_form_$a
});
I'm not sure if I understand completely... but the issue you're having is that, when a user hits the 'submit' button for a given set of values (a given department), it submits ALL of the data on the page? And you only want the input fields for that specific area submitted?
Section off forms with the tag:
<form> </form>
So, you'll have multiple areas:
while(...) {
<form method="..." name="form $a">
<input name="... $a">
<input name="... $a">
...
<submit>
</form>
}
(Obviously this is pseudocode, adjust accordingly)

PHP if statement with checkbox error

Sorry for the dumb question, though I'm a little new to PHP.
I've tried a lot of other ways to do this, but simply couldn't get this to work... Actually I want it to make it that I can have different functions attached to each checkbox that when a user selects a checkbox or another, and clicks the submit button, it triggers the specific functions. But I cannot get the checkboxes to work. It either works with only one selected, or if I check the 1st one then the 4th one, it outputs the 4th's code.
Any other ways of doing this?
Here is my attempt:
1.php
<form method="POST" action="2.php">
<input type="checkbox" name="test[]" value="test1" />test1<br />
<input type="checkbox" name="test[]" value="test2" />test2<br />
<input type="submit" name="submit" value="submit" />
</form>
2.php
$val = $_POST['test'];
if(isset($val)==true){
for($i = 0 ; $i<count($val) ; $i++){
if($val=='test1'){
echo $val;
die();
}elseif($val=='test2'){
echo $val;
die();
}else{
echo "fail";
die();
}
}
}else{
return false;
}
Thank you.
Try:
$vals = $_POST['test'];
$valsCount = count($vals);
if ($valsCount > 0) {
foreach ($vals as $val) {
switch ($val) {
case 'test1':
echo $val;
break;
case 'test2':
echo $val;
break;
default:
echo 'Fail';
break;
}
}
}
As another option, if you're looking to call functions based on the value of the checkbox, you could do something like this ...
I've compressed it all into one file for simplicity, but this is the general idea ...
<form method="post" action="<?php echo $_SREVER['PHP_SELF']; ?>">
<input type="checkbox" name="boxes[]" value="box1">Box 1</input><br />
<input type="checkbox" name="boxes[]" value="box2">Box 2</input><br />
<input type="checkbox" name="boxes[]" value="box3">Box 3</input><br />
<input type="checkbox" name="boxes[]" value="box4">Box 4</input><br />
<input type="checkbox" name="boxes[]" value="box5">Box 5</input><br />
<input type="submit" value="Go!" />
</form>
<?php
class boxProcessor
{
public function box1()
{
echo "<p>You've found box 1.</p>";
}
public function box2()
{
echo "<p>You've found box 2.</p>";
}
public function box3()
{
echo "<p>You've found box 3.</p>";
}
public function box4()
{
echo "<p>You've found box 4.</p>";
}
public function box5()
{
echo "<p>You've found box 5.</p>";
}
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$boxes = $_POST['boxes'];
if(empty($boxes)){
echo "<p>Nothing to do ...</p>";
} else {
$proc = new boxProcessor();
foreach($boxes as $box){
$proc->$box();
}
}
}
?>
You're pretty close with your code as is, you just have to take into account array indexes.
for ($i = 0, $length = count($val); $i < $length; $i++)
{
// add [$i] to $val to access an index of $val
if ($val[$i] == 'test1')
Try changing the names from test1[] to test1 in 1.php and also check a typo on line 7- 2.php.
Hope this helps.
There are a couple of issues that probably don't have anything to do with the real problem:
1) You talk about "1st" and "4th" checkboxes ... but your code only shows two checkboxes
2) Your example misspells "tes2" (so PHP won't/can't find it)
3) You should probably get rid of all the "die()" clauses
SUGGESTION:
Check out this link:
http://www.html-form-guide.com/php-form/php-form-checkbox.html

Need Transfer Value PHP

I am creating a new website. For that website I will need to transfer a quantity and amount value from one if condition statement into another if condition statement. Both if statements are accessed by separate submit buttons named "checkamt" & "buy".
I need to transfer the "quantity", "value", and "net" values to and from the checkamt if statement to the buy if statement.
Here's my code:
<form action="index.php" method="post">
<input type="submit" name="checkamt" value="Check Amount"/>
<input type="submit" name="buy" value="Buy"/>
</form>
<?php
if(isset($_POST[checkamt]))
{
$qun=1;
$val=5000;
$total=$qun*$val;
}
if(isset($_POST[buy]))
{
echo $qun;
echo $val;
echo $total;
}
?>
I think that the problem you're having is that variables don't persist on page change. If you want that, you'll need to use a session. First, you must call session_start before anything, including HTML, is sent to the user. Then, you can use the $_SESSION variable.
<?php
session_start();
?>
<form action="index.php" method="post">
<input type="submit" name="checkamt" value="Check Amount"/>
<input type="submit" name="buy" value="Buy"/>
</form>
<?php
if(isset($_POST[checkamt]))
{
$_SESSION['qun']=1;
$_SESSION['val']=5000;
$_SESSION['total']=$qun*$val;
}
if(isset($_POST[buy]))
{
echo $_SESSION['qun'];
echo $_SESSION['val'];
echo $_SESSION['total'];
}
?>
Improve your English! Not sure if this is what you want, but if you want to share the values of your variables between the two ifs? You have to declare them at a higher scope than your if:
<?php
$qun = 0;
$val = 0;
$total = 0;
if(isset($_POST[checkamt]))
{
$qun=1;
$val=5000;
$total=$qun*$val;
}
if(isset($_POST[buy]))
{
echo $qun;
echo $val;
echo $total;
}
?>
Not sure if I'm getting the question right, but why not do something like this :
if(isset($_POST[checkamt]) || isset($_POST[buy]))
{
$qun=1;
$val=5000;
$total=$qun*$val;
echo $qun;
echo $val;
echo $total;
}
You need to track your variables between the different forms. You can use SESSION like Xeon06 suggested, or do the following. I'm only showing for $qun:
<?php
if(isset($_POST['checkamt'])) {
$qun=1;
}
if(isset($_POST['buy'])) {
echo $qun;
}
?>
<form action="index.php" method="post">
<input type="hidden" name="qun" value="<?php echo $qun; ?>" />
<input type="submit" name="checkamt" value="Check Amount"/>
<input type="submit" name="buy" value="Buy"/>
</form>

Categories