How to make multiple checkboxes work with php and sql - php

How would I pass an array of multiple checkboxes and values through php, saving to a sql database, as well as being able to pull up the saved data back on the client side?
For example, I have an array that saves checkbox values in the way of '"checked"""checked""""', but not only do I want to save the checked value, I also want to save the form data, as follows :
Apples : Checked
Oranges : Not Checked
Bananas : Checked
Tomatoes : Checked
Any help would be GREATLY appreciated, please answer with context of how to do, not just code - still learning!
Here is the code THAT WORKS for this question
processing code :
$salesman = $data['data-invoice-salesman']; // this is an array
$salesman_array = array(); // create new array
$salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User");
for($i = 1; $i <= 5; $i++){ // loop from 1 to 5
if(in_array($i, $salesman)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
$salesman_array[$salesman_names[$i]] = "checked";
} else {
$salesman_array[$salesman_names[$i]] = "";
}
}
$salesman_json = mysqli_real_escape_string($this->_con, json_encode($salesman_array)); // encode the array into JSON and then escape it.
form code THAT WORKS :
<?php
$salesmand = json_decode($invoice['Invoice']['salesman'], true);
$salesman_names = array(1 => "User1",2 => "User2",3 => "User3",4 => "User4",5 => "User5");
foreach ($salesman_names AS $i => $name) {
if ($salesman[$name] == "checked") {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
} else {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
}
}
?>
</div>

Add an array that maps the indexes to the name:
$salesman_names = array(
1 => "Joe Smith",
2 => "Fred Flintston",
3 => "George Jetson",
4 => "John Hamm",
5 => "Alan Smithee"
);
Then in your loop, you can do:
$salesman_array[$salesan_names[$i]] = "checked";
The JSON that's saved in the database might then look like:
{"Joe Smith":"checked", "Fred Flintson": "", "George Jetson","checked", "John Hamm":"", "Alan Smithee":""}
To display the checkboxes, you would refer to the $salesman_array when displaying it:
$salesman = json_decode($invoice['Invoice']['salesman'], true);
foreach ($salesman_names AS $i => $name) {
if ($salesman[$name] == "checked") {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$name.'<br>';
} else {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" /> '.$name.'<br>';
}
}

Related

Extract value from array then run if on value

I have an array of items (cheese) in a checkbox format like so
array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),
The values of the array are displayed on a page (in a hidden div) using the heredoc declaration with an if to check if the checkbox has been used - if the return is empty the div does not show - if one of the checkboxes is "checked" then it does.
///Cheese selections
if (!empty($cheesbox)) {
$output .= <<< OUTPUT
<br />
<div class="sides">Comes with: <p>{$cheesebox}</p></div>
<br />
OUTPUT4;
}
What I need to do is pull any one of the values in the array and if its in the $cheesebox the do something.
Ive tried using an ifelse like this
if ( ('$cheesebox') == "Cheddar" ){
echo "Your topping is Cheddar";
}
elseif ( ('$cheesebox') == "Gouda" ){
{
echo "Your topping is Gouda";
}
elseif ( ('$cheesebox') == "Bleu" ){
{
echo "Your topping is Bleu";
}
however this does not work - I'm sure I have it wrong somehere along the line or does the heredoc function only allow for one?
if so is there a way to accomplish this?
Single quotes in PHP mean a literal string with no parsing of variables. Try this:
if ($cheesebox == "Cheddar") {
echo "Your topping is Cheddar";
} else if ($cheesebox == "Gouda") {
echo "Your topping is Gouda";
} else if ($cheesebox == "Bleu") {
echo "Your topping is Bleu";
}
Better yet:
if (in_array($cheesebox, ['Cheddar', 'Gouda', 'Bleu'])) {
echo "Your topping is {$cheesebox}";
}
EDIT: In response to your further requirements in the comments:
In your PHP:
$cheeses = ['Cheddar', 'Gouda', 'Bleu'];
$cheeseBoxes = '';
foreach ($cheeses as $cheese) {
$cheeseClass = $cheesebox == $cheese ? '' : 'cheese-hidden';
$cheeseBoxes .= <<<CHEESE
<div class="cheese {$cheeseClass}">
<p>Cheese: {$cheese}</p>
<img src="/images/cheeses/{$cheese}.png" alt="A picture of some {$cheese}" />
</div>
CHEESE;
}
// Then, wherever you need it, or just use $cheeseBoxes in your chosen heredoc:
echo $cheeseBoxes;
In your CSS, to hide the inactive ones:
.cheese.cheese-hidden {
display: none;
}

Creating code logic that uses a for loop to cycle through several arrays

I'm trying to create a code logic by using a for loop instead of multiple if statements.
This is the previous if statement code I used before:
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct[0];
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect[0];
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect[0];
}
};
This code allows me to check for the answer and print either the $correct or $incorrect variable. My issue in this code is that it is very inefficient because I end up having to create ten or so if statements.
I came up with a mock-up of the for loop code to illustrate:
$_SESSION["totalCorrect"] = 0;
if (!isset($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
$postAns = array($_POST['answer1'] as $ans1, $_POST['answer2'] as $ans2, $_POST['answer3'] as $ans3, $_POST['answer4'] as $ans4, $_POST['answer5'] as $ans5, $_POST['answer6'] as $ans6,
$_POST['answer7'] as $ans7, $_POST['answer8'] as $ans8, $_POST['answer9'] as $ans9, $_POST['answer10'] as $ans10);
for ($i = 0; $i < count($postAns); i++)
{
if ($i == $postAns[])
{
if ($postAns[] === 'answer')
{
print $correct[];
$_SESSION["totalCorrect"]++;
}
else ()
{
print $incorrect[];
}
}
};
For this code, I have three arrays involved that I am trying to cycle through, $postAns, $correct, and $incorrect. The $correct and $incorrect arrays, when called, print out text depending on whether they got the answer right.
So for the for loop, I want to be able to cycle through each value of the $postAns array to check and and see which answer number it is and whether it is the correct answer or not. If it's correct, then the code cycles through $correct to get the right text for that answer number and increments the value of totalCorrect, the variable that stores how many the user got right. If incorrect, the code cycles through $incorrect to get the right text for that answer number.
I'm not really proficient with loops in general so any insight/help would be greatly appreciated.
EDIT: Included the form submission code
<form action="staff_info.php" method="get" id="q1">
<fieldset>
<legend>Question 1</legend>
<input type="radio" name="answer1" value="1a" id="1a"><label for="1a"> A. </label>
<input type="radio" name="answer1" value="1b" id="1b"><label for="1b"> B. </label>
<input type="radio" name="answer1" value="1c" id="1c"><label for="1c"> C. </label>
<input type="radio" name="answer1" value="1d" id="1d"><label for="1d"> D. </label>
<input type="button" id="answer" class="button " title="abutton" value="ANSWER">
NEXT
</fieldset>
The one thing you're missing in your pseudo code is the actual answers. If you create an array of correct answers as #fefe indicated then the loop will be something like this:
$correctAnswers = array(
'answer1'=>'1d',
'answer2' => '2b',
'answer3' => '3c',
'answer4' => '4b',
'answer5' => '5a'
);
$numberCorrect = 0;
$responseIndex = 0;
foreach ($correctAnswers as $key=>$answer) {
if ($_POST[$key] === $answer) {
$numberCorrect++;
print $correct[$responseIndex];
}
else {
print $incorrect[$responseIndex];
}
$responseIndex++;
}
I don't really know what you trying to achieve but the loop should look something like this and you can make some validation with if or switch case.
$postAns = array(
'answer1'=>'ans1',
'answer2' => 'ans2',
'answer3' => 'ans3',
'answer4' => 'ans4',
'answer5' => 'ans5',
'answer6' => 'ans6',
'answer7' => 'ans7',
'answer8' => 'ans8',
'answer9' => 'ans9',
'answer10' => 'ans9'
);
foreach ($postAns as $key=>$ans) {
var_dump($ans);
}

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!

post array keep only 1 value

PHP FORM CODE :
echo '<form name="planeSeat" action="koltuk-sec-process.php" method="post" >';
...
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork" value="'.$rightplace.'" />';
...
echo '<input type="submit" name="formSubmit" value="Üye girişi yapmadan devam et"/>';
PHP PROCESS CODE :
$rest1 = array();
$rest2 = array();
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);
if($rest1 != null){
print_r ($rest1);
}
if($rest2 != null){
print_r ($rest2);
}
When I send artwork, if I selected 2 checkboxes, $rest1 only keeps the last value. How can I send my all values?
You probably wanted to code
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest1[] = htmlspecialchars($_POST["artwork2"]);
instead of
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);
For one result, break should do the trick:
$foobar = array('uno', 'dos', 'tres');
foreach ($foobar as $fb) {
echo '<p>'.$fb.'</p>';
break;
}
the reason is simple : in case of multiple checkbox checked with the same name, you have to specified an array for the checkbox name, this way you will be able to traverse the posted values
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'" />';
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'" />'; // second checkbox
print_r ( $_POST['artwork'] ) // will display the artwork array
all of your checkbox with similar content should have the same name !!!!!

Input custom attribute value : retrieve and loop in PHP

When I click on buttons I generate some inputs field with custom attributes like that :
<input type='text' name='field["+ i++ +"]' value='' data-kind='title' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='video' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='text' />
I retrieve the 'name' value with a foreach loop in PHP :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => $this->input->post('field_type') // HERE
);
echo '<pre>';print_r($data);echo '</pre>';
}
To get the 'type' I do a $this->input->post('field_type'); which is given by this :
var field_type = $(":input[data-kind]").attr('data-kind');
$("#field_type").val(field_type' ');
and :
echo '<input type="hidden" id="field_type" name="field_type" value="" />';
But it only returns me the last 'data-kind' value not each one :/
Now i just need to loop the 'data-kind' value for each input fields and retrieve them in my foreach loop
Any help would be very very appreciated !!
Many thanks for your answers, it helped me a lot! But now how can I add the result in my current foreach at 'type' data :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => // HERE I NEED EACH ATTRIBUTE VALUE
);
echo '<pre>';print_r($data);echo '</pre>';
}
If you want to place all of the data-kind values in the #field_type field, you need something like this:
var fieldTypes = [];
$("input[data-kind]").each(function()
{
fieldTypes.push( $(this).attr('data-kind') );
});
$("#field_type").val(fieldTypes.join(','));
Maybe you've missed the plus sign?
$("#field_type").val(field_type' ');
should be $("#field_type").val(field_type+' ');
This code:
http://jsfiddle.net/PKgkU/17/
Does what you want!
$('input').each(function(el) {
switch ($(this).data('kind')) {
case "video":
kind = 'video';
break;
case "image":
kind = 'image';
break;
case "title":
kind = 'title';
break;
default:
break;
}
$(this).after('<input type="hidden" id="field_type" name="field_type" value="' + kind + '" />');
});

Categories