Making a checkbox recognize its intended data - php

Level: PHP Learner
I'm stuck with a checkbox problem. I have a db that contains names and unique id numbers.
Using a query, I am pulling a selection of students and showing them to a user in an ultra simple HTML table on a form. Each row begins with a checkbox. The method is POST. So far, so good. My table looks like this:
+-----------+----------+----------+
| SELECT | NAME | ID |
+-----------+----------+----------+
| [] | John | 2233 |
+-----------+----------+----------+
| [] | Susie | 5577 |
+-----------+----------+----------+
[-SUBMIT-]
My problem is that I cannot seem to make the checkbox associate with each record's unique ID. Once the user has selected rows and clicked submit, the $_POST array remains empty.
None of my beginners books reference this specific issue. They go through the "regular" checkbox routines that don't involve interacting with rows from a db. I also could not find an issue on Stackoverflow that addresses this. Also tried Google: plenty of stuff on checkboxes, but I couldn't find any that helped me on this problem.

Just do something like this:
<input type="checkbox" name="ids[]" value="2233" /> ... rest of row
<input type="checkbox" name="ids[]" value="5577" /> ... rest of row
Now, in PHP, you can get the selected ids like this:
$ids = $_POST['ids'];
if( empty($ids) ) $ids = array();
This sets $ids to an empty array if the form was submitted without any of the checkboxes checked.

Edit: If your form doesn't get more complex as you describe, take Doug Neiner's approach, as it is way simpler. This approach is right if a table is likely to have a number of columns.
I like to do it this way:
Number the checkboxes sequentially (1 to 100) and add a hidden field connecting the row number to a real database ID:
<input type="checkbox" name="row_1" value="checked">`
<input type='hidden' name='row_1_id' value='2233'>`
Store the total number of rows in another hidden field
<input type='hidden' name='row_total' value='99'>
Then, in the receiving script, iterate from 1 to the total number of rows using for, check whether this row was selected, and get the associated database ID:
for ($i = 1; $i <= $number_of_rows; $i++)
{
if ($_POST["row_$i"] == "checked")
{
$database_id_unsafe = $_POST["row_{$i}_id"];
...
the latter, of course, needs to be properly sanitized and escaped in case it is processed further.

Related

PHP form to edit database entries

I have a MySQL database of my movie collection and I'm working on a little website for searching and editing the database. The whole project is more of learning thing then just trying to get it done the easiest way. So I am writing it all from scratch, just plain text files, and I am using mostly PHP.
So I want a page where I can edit the information about a movie. Adding new information is fairly straightfoward, but what about removing information. I have several checkboxes for genres. When the form comes up, any genre currently related to the movie is checked. I want to be able to uncheck a box and then that genre will be dropped from that movie. The only way I can think to do this is create an initial array of values when the form opens, and get the POST array when the form is submitted. Then delete any genres in the first but not the second array. This seems kind of messy, and I feel like there should be a more elegant way to do this. This seems like a pretty standard thing to so maybe people have a nice way to do this?
The best way I can think of is to have a many-to-many relationship between genres and movies (meaning a movie can have multiple genre and one genre can appear on many movies).
This involves adding two more tables, one to define the genres, and one to associate them with movies:
genres
---------
id | name
Here's the slightly tricky part:
genres-movies
-------------------
movie_id | genre_id
Where movie_id is an actual ID from the movies table, and genre_id is an actual ID from the genres table.
For instance, genre with the ID of 1 is Science Fiction, and the movie with the ID of 42 is Hitchhiker's Guide to the Galaxy (see what I did there?), this means that if I have the entry 42 | 1 at the genres-movies, will mean that Hitchiker's Guide to the Galaxy is a Science Fiction. Note that neither movie_id nor genre_id are unique, both can appear multiple times, so the following is possible:
movie_id | genre_id
---------+---------
1 | 2
1 | 3
2 | 2
3 | 1
To find all the genres of a movie:
SELECT `genre_id` FROM `genres-movies` WHERE `movie_id` = <ID>;
After all the background, to your question. With that approach, you need multiple queries, remove all genres from a movie, then each to add the ones you selected. You have to do that because checkboxes that were not selected are not sent to the server (pseudo code)
DELETE FROM `genres-movies` WHERE `movie_id` = <ID>; --Remove all genres
foreach ($genres_from_checkboxes as $genre) {
INSERT INTO `genres-movies` (`movie_id`, `genre_id`) VALUES (:movie_id, :genre_id)
}
NOTE! Always sanitize (or better yet prepare!!!) queries with data that came from the user!
Phew! That was long, hope you learned a thing or two :)
You can use input checkbox click event to call an ajax action.
Using jquery (http://api.jquery.com/jQuery.ajax/):
$(document).ready(function() {
$("#form input[type=checkbox]").click(function() {
$.ajax({
url : '/sample/'+$(this).attr('any_id')+'/'+$(this).attr('other_id'),
error: function(){alert('error')},
success : function(data){alert('success')}
});
});
});
And than parse the url to get what you need, and on success function update your form and/or page information using jquery functions like $('element').html() and others.
Another option if you prefer pass the serialized data option for this same function:
$(document).ready(function() {
$("#form.checkboxes input[type=checkbox]").click(function() {
$.ajax({
url : '/sample-form-action',
type: "POST",
data: $("#form.checkboxes").serialize(),
error: function(){alert('error')},
success : function(data){alert('success')}
},
});
});
you can create the form tag around the checkboxes, in this case you can ajax post just the information you really need:
<form name="checkboxes" class="checkboxes">
<input type="checkbox" />
</form>
You can use php if statement to check the value in database column and display checked
<input name="column" type="radio" value="1" <?php if($table['column'] = 1) echo "checked" ?>>
<input name="column" type="radio" value="0" <?php if($table['column'] = 0) echo "checked" ?>>
OR if you are using checkbox
<input name="column" type="checkbox" value="1" <?php if($table['column'] = 1){ echo "checked" }elseif($table['column'] = ){ echo "" } ?>>
i hope that will work for you

PHP Insert Form Response Into Separate MySQL Tables / Rows

I have a form that, upon being submitted via POST, needs to be inserted into two separate tables based on the field. Each field needs to be added as its own line.
Imagine a survey; there are four sections total. For each question within a section, the user selects a value between 1 and 5. There is also an optional notes text area at the bottom of each section.
Each question has its own unique ID in the database in a "questions" table. These questions contain the ID of the section ("sections" table) it belongs to for reference.
Question 1:
How can I insert each answer as its own row in a table called "answers" with the ID of the question?
The structure for "answers" looks like:
id (AI) | question_id | value (user submitted, 1-5) | response_id
Question 2:
How can I then insert each note for each section into a table called "notes" with the id of each section?
The structure for "notes" looks like:
id (AI) | section_id | value (user submitted) | response_id
Response_id is the resulting ID of inserting the user's response into a table called "responses." This table ties it all together for outputting the results for each user submitted response.
Thanks in advance.
You might want to use an array to keep track of the ids you need.
Your HTML block should look something along the lines of:
<h3>Question '.$questionId.': Your question title here</h3>
<input type="hidden" name="question_id" value="'.$questionId.'" /> //Not necessary, but just to show you that a hidden field can be useful too
<input type="text" name="answer['.$questionId.']" />
Then you just use the $_POST data as a regular array, in a for loop or in a big query (better performance depending on the amount of fields/data you are dealing with).
More info on multidimensional arrays in this post: Submitting a multidimensional array via POST with php
You can do one thing like this may be. You said you have question id for each question right so when user selects answer give name to each question like this
name = "question[<?php echo $question_id ?>]"
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
For the not just give simple name. When user submits it take the entire question[$ids] array loop through each id and insert into answers table using question id. You need to little bit of array operations.
For Notes you just use section id for in the name field and insert into database normally.

how to update database records using form

There are number of records which I gather them from mysql say thease:
id name mark
1234 john 18
53 smith 12
324 mike 15
...
I want to build a form to give ability to edit(update) all marks at once
I know that I can show them at the form using textbox value property.
But how can I Identify the exact same record when I want to process the posted form, in order to update the correct filed? and surly, I don't know how many records are there in the form.
The idea might be identifying the records through the id field.
but how to do that?
If this application is for administrative use only:
<input type="hidden" name="id" id="id" value="_ID_VALUE_" />
<input type="text" name="name" id="name" value="_NAME_VALUE_" />
<input type="text" name="mark" id="mark" value="_MARK_VALUE_" />
then
UPDATE table SET mark = '_SANITIZED_MARK_VALUE_' WHERE id = "_SANITIZED_ID_VALUE_";
If it's an application for the end user, you don't want to trust that he/she won't change the value of the hidden input. In this case, you'll most likely want to store the id, name, and mark in a $_SESSION variable and do comparisons on the post to figure out which record pertains to which id, and then build your update statement accordingly.
When you build your form, use the ID from the database as part of each text field's NAME attribute. Then when you receive your array of posted values, you can process the keys to find out the ID of the record you should be updating. For example, you could have your fields named "record-1234", "record-53", etc. Then you would iterate over the keys in $_POST, split them on "-" and use the resulting IDs in your UPDATE query.

PHP MYSQL edit form, trying to implode/explode row to checkboxes?

I have a form that has multiple categories. They are separated by checkboxes, so one could check any number of categories that their post/story will be in.
The values are stored inside a db row separating them by commas while INSERT
GetSQLValueString(implode($_POST['r_category'],", "), "text"),
So in the database I could have an entry that looks like this:
2,3,6,12
Which those are category numbers.
I am now building an edit form feature to use to Edit and UPDATE these records. I can not find a way to "EXPLODE" the values into checkboxes on the edit form??
So if you log in and go to the ENTRY that you want to edit for example, I have Checkboxes separating the Categories, so it will be easy to check and uncheck to add and not add... I have tried everything I could to get the values to POST and be checked when viewing this Edit Form.
Here is an example of one of my Category Check boxes on my edit form page, but it is not working when I have multiple Categories, like the example above.. 2,3,6,12 ?? :
<input type="checkbox" name="r_category[]"
<?php if (!(strcmp("2", $row_Recordset2['r_category']))) {
echo "checked=\"checked\"";} ?> value="2" />Cat 2
Thanks in advance NINJAS!!
I can not find a way to "EXPLODE" the values into checkboxes on the edit form
This line is so close to the answer that I'm seriously wondering if this is a joke post.
Given your database structure as it is, you can use the explode() function to break the value into an array based on a delimiter. For example:
$values = "1,2,3,4";
$array_of_values = explode(",", $values);
After this, $array_of_values will contain an array of four elements with the values of 1, 2, 3, and 4 respectively.
When deciding whether or not to display the checkbox as checked, you can use the in_array() function to make that call:
if (in_array("2", $array_of_values)) {
echo 'checked="checked"';
}
Beyond that, let me take this opportunity to second what #MarkB said in the comments on this question: it's a bad idea to hold multiple values in a single database field. It makes searching for things harder, it makes adding values harder... it just makes everything more complex than it needs to be.
The best way to handle this would be to have a many-to-many table which stores rows of items and categories, with one row for each category that an item belongs to.
In other words, where you currently have this:
Item | Category
---------------
123 | 1,2,3,4
You would instead have a table that looks like this:
Item | Category
---------------
123 | 1
123 | 2
123 | 3
123 | 4
You can use it as shown below it could be helpful
if (in_array("2", $row_Recordset2['r_category'])) {echo "Checked";}
That in_array conditional never did work for me. I devised a totally front-end solution instead that works like a charm and automatically updates itself based on changes to the database. If you're interested, check it out here.
https://stackoverflow.com/a/26433841/1896348

Writing specific values to a database X times?

To begin with, i should clarify the title, so you really understand what I'm trying to do.
I'm working on a shopping-cart-ish script, but it's a little different because all products (almost always) will be purchased each time. Therefore i believe it's best to list all of the items up with a table, and then let the customer choose the amount of each product they want.
It'd look something like this:
-- Name ------------------------- Amount --
-- A random product ------------- 15 ------
-- Another random product ------- 2 -------
-- And a third one --- ---------- 19 ------
-- ------------------------------ ---------
-- ------------------------------ SUBMIT --
The problem is, I'm not sure how to write it into the database. Or more specific, i don't know how to submit the data in a way that i get all of the chosen products, as well as the amount of each one into an array. I might add more products to the database later, so i can't hardcode it in.
I can't post two values in one input, which is too bad. If i could do that i could post the ID and the amount as two different values.
Any ideas how to do this?
When you create your input fields, use an array for the name, with the product id as the key.
For example (where $product_id is the ID of the product that the amount corresponds to):
<input type="text" name="amounts[<?=$product_id?>]">
Then in PHP, after the form is posted, $_POST['amounts'] will be an array, where the keys are the product IDs, and the values are the actual amounts. You do not need to do anything special for this to happen; by default, PHP will recognize that GET/POST data that contains []s should be made into an array.
Then you can just iterate over this array to update the database:
foreach ($_POST['amounts'] as $product_id => $amount)
{
if (!empty($amount)) // was a value given for this amount?
{
// build your insert query here
}
}
concatenate the productID and the qty with a pipe "|" so it would be
productId=14
Qty= 3
inserted value= 14|3
then after your db fetch, you can explode the data by the "|" and have part1=14 and part2=3

Categories