Fetching data from database into checkbox - php

I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.
Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).
In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back
Desired output
I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.
PS: I am a beginner and my english is not really good.
Controller
$item = Item::findOrFail($id);
return view('edit',compact('item'));
HTML
<div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="" value="" />
</div>
JSON

If I understood the question correctly, you want to see if chicken wings (or any other food) is set and if it is, output a checked check box.
What you can do is use an if(strlen($json_file['name']) > 0) to see if chicken wings has text or not and then do /> Chicken wings.
Example:
<?php
if(strlen($json_file['name']) > 0) {
?>
<input type="checkbox" <? echo 'checked="checked"'; ?> />
}
?>
I realized that the name could be set but have another name such as chicken breasts instead of wings, you can do an if($json_file['name'] == 'Chicken wings') {}.
Good luck!

this is one of my issue back then in checkbox, you can use tenary to check the checkbox if there is a value for that attribute. Try this one,
<div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="item_checked" value="1" {{ $item->item_checked ? 'checked' : '' }} />
</div>
Hope this helps :)

Related

Inserting values to the database with hidden fields and checkbox

Good day!
Im currently having problems with inserting values with checkbox and hidden field. Any tips or solutions are greatly appreciated.
So my problem is this: I have a form with only checkboxes in it and a submit button and If I check one of the values in a checkbox a hidden upload field will be displayed the hidden value must be connected to the chosen value in the checkbox. How can I insert the hidden value to the corresponding checkbox value in a database. For example
HTML:
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
PHP:(Updated) This is what I have now. when I dont check the 1st checkbox. the hidden_one in the 2nd checkbox isnt inserting
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
$sql = "INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one')";
$result = mysqli_query($connection, $sql);
}
If I check value 1 and entered a sample1 in the hidden form and I check value 2 and entered a sample2 in the hidden form. sample 1 must be in the same column as value 1 and sample 2 must be in the same column as value 2. its not inserting properly
UPDATE:
So I changed the code into this
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
but the problem is sometimes its not inserting correctly. Sometimes hidden_one is empty in the database. I'm really lost at the moment. Can't find a solution elsewhere.
This is my updated form
Im seeing a pattern, when I skipped a checkbox like I check value1 then skip value2 then check value3. value3 hidden isn't inserted. Still not solved :( lol this is driving me crazy. at the verge of quitting. lol
One way you could insert the value of your checkbox into your hidden input fields, is by making a click function that takes $(this).val(), which is your clicked elements value. You can then put that value into a variable. You then go to target the parent element/container for the targeted checkbox and find the corresponding input field. You then simply set the value of that input field with the declared value of the checkbox.
Note that the notation for this JavaScript is in jQuery, and you will need to include a jQuery library in order for this solution to work.
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
Example:
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 1">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 2">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
Direct JS Fiddle link
When it comes to inserting the value(s) into the database, it's hard for me to give a concise answer, because I don't have any debugging information on your application, so I don't know if you have structered it properly. I would assume you have either an AJAX function or a form action to post your values. As you noted in your own attempt, is that the values come up as an array that you will have to loop through. However, I am uncertain of the nested foreach loops.
Let me know if you need any further assistance, and in that case, update your question with potential error messages, corresponding form/ajax code, and if your PHP file holds any other relevant information, add that too.
A rough example could be:
<?php
$hidden_one_array=array_values($_POST['hidden_one']); //our posted array
$i=0; // iterator
$length=count($hidden_one_array); //length of the array
while($i < $length) {
$sql="INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one_array[$i]')";
$result=mysqli_query($connection, $sql);
$i++;
}
?>
What we're doing here is basically looping through the array, using the iterator value as our index pointer to each respective array index to insert into the database.
Also note that you should probably look into prepared statements to prevent sql injection. You are already using mysqli_ so might as well take advantage of it.

Passing checkbox checked from jQuery to PHP in CodeIgniter

I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1

How to store data if checkbox is selected

I'm doing this one using PHP.
I'm doing some basic quiz application and it has a backend. On my backend, I am setting up a quiz for students to answer. One of my interface is like this.
If the user checked the box, it means 1950 is the answer. How would I process that one in my database to determine that 1950 has been the answer of the question.
My Database is like this.
tbl_choices
Id,Choice,isAnswer
so ideally, it would be stored like this.
tbl_choices
ID CHOICE isAnswer
001 1900 0
002 1800 0
003 1950 1
004 1850 0
My question here is how would I code it in a sense when a user will check the checkbox and the textinput right beside it will have a value of isAnswer as 1.
Just an additional info: When a user will click that + button it will add a new textinput and if user will click - button it will delete a textinput, but I got that all covered.
The choices are dynamic, it will changed, that above that I've shown you is just an example.
P.S: Sorry for the title, I don't know what's the title of this kind of question :-)
Your help would be greatly appreciated and rewarded!
you can try html like this :
<input type="checkbox" value="1900" name="answer1[]">
<input type="text" value="1900" name="answer2[]" />
<input type="checkbox" value="1800" name="answer1[]">
<input type="text" value="1800" name="answer2[]" />
<input type="checkbox" value="1950" name="answer1[]">
<input type="text" value="1950" name="answer2[]" />
<input type="checkbox" value="1850" name="answer1[]">
<input type="text" value="1850" name="answer2[]" />
and then use php code:
foreach($_POST['answer2'] as $v){
if(in_array($v, $_POST['answer1'])) {
$s = 1;
}else
$s = 0;
$sql = "INSERT INTO table VALUES(null, $v, $s)";
}
also on click plus update values of both check box and text field
in general you can use checkboxes as an array when submiting information, just name the checkboxes as an array like
<input type="checkbox" value="1900" name="answer1[]">
<input type="checkbox" value="1800" name="answer1[]">
<input type="checkbox" value="1950" name="answer1[]">
<input type="checkbox" value="1850" name="answer1[]">
then on the server side you handle $_POST["answer1"] as an array and cycle through the possible answers, something like this
if (is_array($_POST["answer1"]))
{
foreach($_POST["answer1"] as $answer)
{
// insert into database here
}
}
important: this will only show what a user actualy selected, if an option is not clicked then it will not be part of the array
I think it would make sense to have more than one table, one for the questions with their options and then one for the answers with the fields id, choice_id. Otherwise it is going to make generating the questions a lot more difficult especially when a number of students answer the same question?
One more thing, you could add up in the answers of your question, add row and delete row based on + and - button.
The code for that:
<script type="text/javascript">
$(document).ready(function() {
$("#plus").click(function() {
$('#mytable2 tbody>tr:last').clone(true).
insertAfter('#mytable2 tbody>tr:last');
$('#mytable2 tbody>tr:last #st').val('');
$('#mytable2 tbody>tr:last #newst').val('');
$('#mytable2 tbody>tr:last #plus').val('+');
return false;
});
});
for more detail, you may refer following link:
Add Row on Button click

How to handle 2 radio buttons per search result with php

When my user searches for game in my DB, I present them with a list of the games that match their search term, and then i want to add a button to each item that allows the user to select "have it" or "want it" then have a single "add" button that adds their selections to their profile.
because you cant have it and want it at the same time, i assumed a radio button would be the best choice.
but now i am lost as to how to handle the buttons. When i click on one selection from the search, it will deselect when i choose have or want on another game.
I understand that i should be creating a separately name form for each search result, but then how would i manage the data when sending it to my controller? Maybe i need incrementing form names and then count how many results and use that in my controller?
Also, i need the gameID associated with the selections so i need to send a hidden value with that data for each selection
maybe i am going about this the wrong way...
heres my code
echo '<div id="UserSearchGameResults">';
echo '<form action="#" method="Post">';
$x = 0;
while($gamesLike != null)
{
$x++;
echo '<div id="game_search_list_item">'.$x.'. '.$gamesLike['title'].'</div>
<span class="gamelistblue">
<input type="radio" name="haveOrWant" value="have" />Have it
</span>
<span class="gamelistorange">
<input type="radio" name="haveOrWant" value="want" />Want it
</span>
<input type="hidden" name="gameID" value="'.$gamesLike['ID'].'" />';
$gamesLike = $statement->fetch();
}
$statement->closeCursor();
echo '<br /> <input type="submit" value="Add Game(s)" />';
echo '</div></form>';
any help is appreciated with the subject
new ideas on how to handle my needs are welcome too.
Dan
Use arrays for the input names. Something like
<input type="radio" name="game' . $gamesLike['ID'] . '[haveOrWant]" value="have" />Have it

How do I call up values in PHP for user input in forms (radio buttons and selects)

Ok so my admin sets to edit a book which was created. I know how to bring in the values that were initially entered via a simple text field like 'bookname'. On the edit book page the book name field stores the currently assigned 'bookname' in the field (which is what I want! :) )
However I have other field types like selects and radio button entries...I'm having trouble calling in the already set value when the book was created.
For example, there is a 'booklevel' field, which I have set as radio button entries as; Hard, Normal, and Easy. When the user goes to edit the book, I'm not too sure on how to have the current value drawn up (its stored as text) and the radio button being checked. I.e. 'Normal' is checked if this is what was set when the book was created. So far I have this as the code for the adding book level:
<label>Book Level:</label> <label for="booklevel1" class="radio">Hard
<input type="radio" name="booklevel" id="booklevel1"
value="<?php echo 'Hard'; if (isset($_POST['booklevel'])); ?>"></label>
<label for="booklevel2" class="radio">Medium<input type="radio" name="booklevel"
id="booklevel2"
value="<?php echo 'Normal'; if (isset($_POST['booklevel'])); ?>"></label>
<label for="booklevel" class="radio">Low<input type="radio" name="booklevel"
id="booklevel3"
value="<?php echo 'Easy'; if (isset($_POST['booklevel'])); ?>"></label>
This all works fine by the way when the user adds the book... But does anyone know how in my update book form, I can draw the value of what level has been set, and have the box checked?? To draw up the values in the text fields, I'm simply using:
<?php echo $row['bookname']?>
I also noticed a small issue when I call up the values for my Select options. I have the drop down select field display the currently set user (to read the book!), however, the drop down menu again displays the user in the list available options to select - basically meaning 2 of the same names appear in the list! Is there a way to eliminate the value of the SELECTED option? So far my setup for this is like:
<select name="user_id" id="user_id">
<option value="<?php echo $row['user_id']?>" SELECTED><?php echo $row['fullname']?></option>
<?php
while($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['user_id']?>"><?php echo $row['name']?></option>
<?php } ?>
</select>
If anyone can help me I'll be very greatful. Sorry for the incredibly long question!! :)
For the radio buttons, simply add the attribute checked="true" if the current button's value matches the value you already have. For the dropdown, don't use the first option you have there, but instead use the same technique as the radio buttons, but with selected="true".
Check to see which string is stored in the DB (easy, normal, hard) and then set the checked field to 'checked'. For example:
<label>Book Level:</label> <label for="booklevel1" class="radio">Hard
<input type="radio" name="booklevel" id="booklevel1"
value="hard" <?php if($row['booklevel'] == 'hard') echo 'checked="checked"'; ?>></label>
As to the second part - you'll need to store the first value of $row['user_id'] in a temporary variable before entering the while loop. Then check each additional user_id you receive to determine whether it is equal. If it is, don't print its option. Like so:
<?php
$tmp = $row['user_id'];
while($row = mysql_fetch_array($result)) {
if($row['user_id'] != $tmp) {
echo '<option value="'.$row['user_id'].'">'.$row['name'].'</option>';
}
}
?>

Categories