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
Related
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.
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
I understand the title may be a little vague, but, hopefully, I can explain it here.
We have a page where the user modifies certain fields of a database. The fields being modified change with the selection of a dropdown at the top of the page.
Suppose we have this table by the name of restaurants:
-----------------------------------------------------------
| id | name | items |
-------------------------------------------------------------
| 1 | fryking | burger, fries, shake |
| 2 | burgertown | nuggets, chicken sandwich |
-----------------------------------------------------------
When loaded, the page should look like this:
[ CHOOSE RESTAURANT ] [v]
ITEMS:
With "fryking" selected, the user can: view fryking's items, add new items, remove unwanted items.
[ fryking ] [v]
ITEMS:
[ (txtbox) ] [ADD ITEM]
1. burger [DELETE]
2. fries [DELETE]
3. shake [DELETE]
Once a restaurant has been selected, the user should be able to add, delete, etc. without the dropdown reverting to "SELECT RESTAURANT" and forcing them to select it again.
Right now, we can display the appropriate information when a restaurant has been selected, but not have the restaurant remain selected after processing an "add" or "delete".
Sorry I couldn't explain this any better. I know this has been done 1000 times on other sites, so someone must understand what I'm looking for.
Please let me know if I can clarify anything.
Many thanks,
Justian Meyer
EDIT:
Here's how the deletes are being handled (each in their separate forms).
$page = str_replace('%7E', '~', $_SERVER['REQUEST_URI']);
...
<form method="post" action="'.$page.'">
<input type="hidden" name="item_id" value="'.$i.'"> // $i refers to the value from the loop
<input type="submit" name="delete_item" value="Delete">
</form>
What could I do to condense every button into one form and still process them properly?
JavaScript:
- set the value of the drop down list in the onload event.
PHP:
- set the selected tag by saying something like
<?
if ($_POST)
{
$ddlRestaurantPersistValue = $_POST['ddlRestaurant'];
}
?>
and the HTML would be
<select id="ddlRestaurant" name="ddlRestaurant">
// build the options here if you are doing a database while loop
// check to see if the option value == $ddlRestaurantPersistValue and then add
// selected='selected' to the attributes of the option
</select>
I dont know what technology you use, but in asp.net mvc i would do something like this
when performing httppost i would save the value (or id or whatever) of the selected dropdown item in a session (or even a variable in the controller) and give it back to the view after the post and set that session or model information as the default.
can you tell what technology you are using?
I don't quietly get what you mean.
Once a restaurant has been selected, the user should be able to add, delete, etc. without the dropdown reverting to "SELECT RESTAURANT" and forcing them to select it again.
Considering I don't get why SELECT RESTAURANT mades a comeback, why just don't select what you want with a javascript code?
You can bind an onchange listener
Well, I think something like this is best handled via AJAX calls, but I won't suggest you re-write the page just to fix one problem.
You are going to have to tell your form processor what the current restaurant is, so it can be set correctly after the save. Assuming you have many forms on the page for a good reason, you are going to have to suck it up and put a hidden restaurant input in every form. Update them all when the user changes the restaurant value (via javascript) and reset the restaurant when building the page after the save.
I'm trying to make an Ajax search form - This form will simply search the database for names.
The table design is as follows:
id name age
1 some name 10
2 some name2 11
3 some name3 12
Each name is associated with a unique ID.
I want to create a drop down menu of top hits when the user enters their search string.
Also, somehow in the background i would like to retrieve the associated ID with each result as well. That ID will be POST'ed to a form say
myform.php
Now, my question is as follows:
1) How do i create the drop down menu?
I believe i can follow this tutorial and simply customise it to create a drop down menu.
http://www.w3schools.com/ajax/ajax_aspphp.asp
This would be fairly simple.
2) The main question is, how do i keep track of the ID and selected name, so that i can POST that ID to myform.php
Thanks.
<select name="carlist">
<option value="id">name</option>
</select>
Keep id and name like this.
on posting id is posting , you can get name from id .
I hope this is what you are asking.
But i dont find drop down in that link you provide
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.