Sum Selected Checkbox Values using PHP - php

I've been figuring out ways on how to work this out but I can't seem to. I'm a beginner in PHP and I'm so lost right now. I want to sum the selected checkboxes's values and post the sum of the values in a PHP page.
Here's my HTML so far
<input class="wrapped-input" type="checkbox" value="290" id="widgetu15650_input" name="custom_U15293[]" tabindex="1"/>
<label for="widgetu15650_input"></label>
Here's my PHP so far
if (isset($_POST['u15175'])) {
if($_POST){
$val = 0;
foreach($_POST['custom_U15293'] as $custom_U15293){
$val += $custom_U15293;
}
echo $val;
}
}

Try this,
if($_POST){
if(isset($_POST['custom_U15293']){
$val = 0;
foreach($_POST['custom_U15293'] as $custom_U15293){
$val += (int) $custom_U15293;
}
echo $val;
} else {
echo 'Value not received';
}
If you see Value not received there is some problem with your HTML code

Related

Unable to use an array as an array?

I am in the process of building a software download site for my company.
However, I have come across a problem that I am unsure how to get past.
I am retrieving all the information from a table about a particular software release and placing them in a multidimensional array. I am then trying to run a foreach (I have even tried a for loop) against that array and I get an error shown below:
When I run var dump against the original array, I get this:
So I am really confused as I don't know what I'm missing or where I am going wrong. The reason why I want to run this is so that I can filter the array into a one dimensional array.
Below is the code for the main web page
<?php
//Displays list of companies in 2 columns
$versionAccess = VersionAccess::findAccess($relId);//This gets set earlier in the webpage
$count = count($versionAccess);
var_dump($versionAccess);
foreach ($versionAccess as $va)
{
if ($va->company_access != '0')
{
$versionAcc[] = $va->comapny_id;
}
}
foreach ($company as $compAccess)
{
$compAccessId = $compAccess->company_id;
if (in_array($compAccessId, $versionAcc))
{
$access = 'checked disabled';
}
else { $access = 'disabled'; }
$accessName = 'access'.$compAccessId;
if ($ctr % 2 == 0)
{
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
else
{
if ($ctr < $compCount)
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
}
else
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
}
$ctr++;
}
?>
The function that brings the data from the database is:
public static function findAccess($accessId)
//find the version access in database
{
return self::findQuery("SELECT * FROM version_access WHERE version_id = '$accessId'");
}
The findQuery method:
public static function findQuery($sql)
{
global $database;
$resultSet = $database->query($sql);
$objectArray = array();
while ($row = mysqli_fetch_array($resultSet))
{
$objectArray[] = self::instant($row);
}
return $objectArray;
}
I am still relatively new and any help is greatly appreciated.

PHP If / Else statement going directly to the Else without waiting for form input

Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.

PhP Radio button in Array

I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.
In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>

Declare php variables by for loop in array

How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.
Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.
<?php
$question = array();
for($j=1; $j<4; $j++) {
$question[j] = $_POST['question[j]'];
$result;
$n=1;
if($question[j] != "") {
$result = $n.'): '.$question[j].'<br/><br/>';
$n++;
}
}
echo $result;
?>
<?php
$question = array();
$result = "";
for($j=1; $j<4; j++) {
$question[$j] = $_POST["question$j"];
if($question[$j] != "") {
$result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>';
}
}
echo $result;
?>
Though you don't need an array.
<?php
$result = "";
for($j=1; $j<4; j++) {
$result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';
}
echo $result;
?>
For starters, arrays are zero-indexed, so I think you want this:
for($j=0; $j<3; j++)
Aside form that, this doesn't evaluate the value of j:
$_POST['question[j]']
I think you might want something like this:
$_POST["question$j"]
However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:
$_POST['question' . $j+1]
You can use following HTML code
<input type="text" name="question[a]" />
<input type="text" name="question[b]" />
<input type="text" name="question[c]" />
with following PHP code:
foreach($_POST["question"] as $key => $value)
{
// $key == "a", "b" or "c"
// $value == field values
}
Remember to sanitize Your input!

HTML multiple checkboxes with identical name= into PHP $_POST

So I have a 3rd party survey tool that generates html surveys, and for multi-select checkboxes in a given question, it will name them all the same:
<input type="checkbox" value="1" id="V25_1" name="V25">
<input type="checkbox" value="2" id="V25_2" name="V25">
Is there a way that all the selected values can be retrieved in PHP?
$_POST by default seems to simply store only the last selected value.
Your code should be approximately the following:
<select multiple="multiple">
<input type="checkbox" value="1" id="V25_1" name="V25[]">
<input type="checkbox" value="2" id="V25_2" name="V25[]">
</select>
V25[] means that you can get the value from an array. e.g. $_GET['V25'][0]
You could also specify an index if needed:
V25[1] or V25[a]
You could run something like this before the form submit:
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("id"));
});
or
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("name")+"[]");
});
It is possible to retrieve all variables when you have multiple elements with identical 'name' parameters.
After much scouring the internet for a solution, I wrote the following php script which grabs the raw post data, and parses it:
<?php
function RawPostToArray() {
$rawPostData = file_get_contents("php://input");
if($rawPostData) {
$rawPostData = explode('&', $rawPostData);
if($rawPostData && is_array($rawPostData) && count($rawPostData)) {
$result = array();
foreach($rawPostData as $entry) {
$thisArray = array();
$split = explode('=', urldecode($entry), 2);
$value = (count($split) == 2) ? $split[1] : '';
if(array_key_exists($split[0], $result)) {
if(is_array($result[$split[0]])) {
$result[$split[0]][] = $value;
}
else {
$thisArray[] = $result[$split[0]];
$thisArray[] = $value;
$result[$split[0]] = $thisArray;
}
}
else {
$result[$split[0]] = $split[1];
}
}
return $result;
}
else return array();
}
else return array();
}
?>
Any duplicate 'names' are bumped down into an array within the result, much the way $_POST does, when the HTML is coded correctly.
There is probably plenty of room for improvement here, and I'm sure not all situations are accounted for, but it works well for my application.
Suggestions are appreciated where improvements can be made.

Categories