I have a list of checkboxes, and it is always growing, so for example..
<li><input type="checkbox" value="19384">Nutrition</li>
<li><input type="checkbox" value="22450">Weight Loss</li>
<li><input type="checkbox" value="98957">Fitness</li>
<li><input type="checkbox" value="34916">Lifestyle</li>
let's say I check Nutrition and Fitness, what is the best database schema/structure to save the checked ones so that I can retrieve it later?
The main problem is that these checkboxes are always increasing in number, so these four tomorrow can go up to 7 checkboxes or 10, and will always increase so I can't setup in database a specific amount of tables for each checkbox value.
I can't understand how I would upload the checked ones to database, and then retrieve them later?
Is it possible for me to upload the values to MySQL of each selected and then when retrieving them I'd have to check between the list and match with the ones that have been uploaded to MySQL and then if so use the checked="yes" in the input? I'm using PHP as well.
The checkbox simply tells you if something is ... wait for it... checked or not. There is one possible value you would get from checking a box and that is that the checkbox has been checked. You will receive nothing if it isn't checked.
The first thing you need to do is make sure the checkbox's state can actually be checked. That means you need to name the checkboxes and don't put a value in them.
<li><input type="checkbox" name="nutrition">Nutrition</li>
<li><input type="checkbox" name="weight_loss">Weight Loss</li>
<li><input type="checkbox" name="fitness">Fitness</li>
<li><input type="checkbox" name="lifestyle">Lifestyle</li>
Now the php that will be checking to see if these are checked or not will look something like:
if (isset($_POST['nutrition']))
{
//Code to process nutrition being checked
}
That's all - you do that for each one that you have.
As far as the database, since you think you'll be modifying the types, then you should create a separate table that relates someone checking one of these checkboxes to another record that has the related information.
For example, you have one table that shows a person:
person_id = auto-incremented integer as primary key
person_name = string/nvarchar/whatever
That's the person table. The next table would be your lookup table:
c_pk = autoincremented integer as primary key
c_checkbox_id =
integer that relates to another table that stores the types of
checkboxes you have
c_person_id = the id of the person the
checkbox_id relates to
The last table would be the table that holds the type of checkboxes:
checkbox_id = autoincremented integer as primary key
checkbox_name =
string representing name of checkbox (nutrition, weight loss, fitness
et al)
That's how you lay it out so that you can add more at any time. You can also build your checkbox list dynamically by querying the table that holds all the checkbox names.
It's a bit much if you are just starting in programming and databases, but it is most definitely the right way to do it.
Related
I realise that this may be a duplicate question but I can't seem to find the right answer.
I'm trying to insert multiple rows into a MySQL table but, at the moment, all I'm doing is inserting the same data multiple times.
The table is called 'tblRoomsBooked' and the fields are bookingNumber, roomID, roomRate and depositRate. The table has it's own unique, primary key, roomBookedID which auto-increments.
We have an HTML form for booking rooms that we hire out. There are four rooms that can be hired in any combination. Each room has its own ID, hire cost and deposit amount required. So, for example, if one room was booked with a deposit, there should be one record inserted consisting of the booking number, the room's ID, the room's cost and its deposit. If three rooms were to be hired, there should be three separate records inserted, each record would hold the room ID, room cost and deposit of each room booked but all the rooms booked at the one time would have the same booking number.
The SQL code is:
$bookingNumber = ($_POST['bookingNumber']);
$roomID = ($_POST['roomID']);
$roomRate = ($_POST['roomRate']);
$depositRate = ($_POST['depositRate']);
$RoomsBooked = "INSERT INTO tblRoomsBooked (bookingNumber, roomID, roomRate, depositRate) VALUES ('$bookingNumber', '$roomID', '$roomRate', '$depositRate')";
If I use $RoomsBooked = "INSERT INTO tblRoomsBooked (bookingNumber, roomID, roomRate, depositRate) VALUES ('$bookingNumber', '$roomID', '$roomRate', '$depositRate'), ('$bookingNumber', '$roomID', '$roomRate', '$depositRate'). ('$bookingNumber', '$roomID', '$roomRate', '$depositRate'), ('$bookingNumber', '$roomID', '$roomRate', '$depositRate')"; as I read elsewhere here, it just creates four rows of the same data, regardless of the combination of rooms selected.
The rooms are selected by checkboxes...
<input type="checkbox" class="checkboxMargins" id="meetingRoom" name="roomID" value="1" onClick="Check();">
<input type="checkbox" class="checkboxMargins" id="library" name="roomID" value="2" onClick="Check();">
<input type="checkbox" class="checkboxMargins" id="jajRoom" name="roomID" value="3" onClick="Check();">
<input type="checkbox" class="checkboxMargins" id="annex" name="roomID" value="4" onClick="Check();">
When a checkbox is selected, some JQuery scripting by JonoJames which can be found here Output Data From MYSQL... is used to fill hidden input boxes for the room costs.
I've tried using name="roomID[] but this throws an error regarding arrays and not liking the INSERT statement.
All this works perfectly for booking one room, it's just if more than one is booked that I can't make work.
I think I need to use for or foreach but the examples on here don't really show how to take the data from the form to insert it into the table.
What I need to know is, if for or foreach is the way to go, what to do and how to use it. If not, what do I need to do?
All it needed was to put a 0 into the JavaScript wherever the value of the deposit was ''
For example. In the JavaScript there are lines similar to document.forms["bookform"].room1valueDeposit.value ='';. This need's to be document.forms["bookform"].room1valueDeposit.value ='0';.
I had tried replacing the '' in the script with0 but I had replaced all '' not just those relating to deposits. This way, if a room was booked but no deposit was required, it would fill the field with a zero not an empty string and if a deposit was required, the deposit amount would be entered.
Can't believe something so small could take so long to figure out.
As you didn't share any information about the HTML code, it is really hard to understand your booking process.
Regarding your multiple inserts, you already stated the correct approach. If you send your formular to the backend, you have to send each Booking of the room to the backend. This array contains multiple objects, depending on how many books have been booked.
Every obect should contain your necesarry data, roomID, roomRate, deposite and more. As you said, yes it is possible to loop through that array and then insert every booking into the database.
The error you get, is that you insert the same data over and over again, because you do not loop or didn't correctly fetch your next booking. If you share more code, we can take a look.
Sorry if this is a stupid question but im really not sure how to tackle this, perhaps im overthinking. I need to retrieve both the name attributes value and the value attributes value. Have a look at img below:
echo'<input type="radio" name="'.$eventId[].'" value="'.$team1.'">';
The name contains the event_id and the value contains user selection. I need the name Ids value to insert event Id into db along with user selection.
I know how to retrieve the rad value attribute but not sure about the name, maybe Im overthinking it or need to change my logic. Any ideas?
If user select Australia radio button than in PHP you will get value 'Australia' but you want the value 'Australia_80' to store in db. Change all your radio button values and names like
<input type="radio" value="Australia_80" name="getRadio">
<input type="radio" value="Canada_81" name="getRadio">
I have a MySQL database with a column of datatype SET (multiple selection, say apples, oranges, grapes)
I want to have a form with checkboxes for those values (apples, oranges, grapes etc) so one can select a breakfast basket type that contains for example, oranges and grapes.
It would pull from the database those baskets with those selection of fruits (specified in the column 'Fruits', which is a EM datatype column. (I have a multiple selection when entering the values for the column.)
Can it be done? Should I make another table with FruitNames?
Also, when I add a new value to the multiple selection list, all my previous entries disappear and I have to re-enter all the values again...
Please help!
How to search for those entries that match the multiple selection (from the SET type column)?
Can I edit the list of values in the SET type column without erasing previous entries?
Thanks in advance.
Yes, you will need another table. That is called database normalization.
Can you show me query that adds values to list?
I will give you PHP code how to implement selection of fruits.
$fruits = implode(',', $_POST['fruits']);
mysql_query('SELECT name, fruit_id FROM fruits WHERE fruit_id IN ('.$fruits.')');
Here is the form
<input type="checkbox" name="fruits[1]"> Apple<br>
<input type="checkbox" name="fruits[2]"> Pear<br>
I have a long questionnaire (46 questions) with each having (3) possible answers, yes, sometimes, and no, (3 radio buttons) each of which have a corresponding value, 10, 5, and -10 respectively.
I had the questions divided up amongst 4 headings with several questions under each heading.
I was able to post all the data to mySQL Database by giving each a different name attribute that corresponded with its field in the Database.
The problem I am having is that I can no longer use the radio buttons as a set, that is, they are all selectable, defeating the purpose of having them, essentially making them check-boxes....
I need to have each radio button its own value in my database and I need them to be grouped in their 3 possible choices for each question...
I will post an example of my form html and php send script....
Thank you in advance for any advice...
html code one question
<div class="questionBox">
<p>1.Have I clearly defined my companies target market?</p>
<input type="radio" name="ca1y" value="10"/>
<label for="ca1">YES</label>
<input type="radio" name="ca1s" value="5"/>
<label for="ca1">SOMEWHAT</label>
<input type="radio" name="ca1n" value="-10"/>
<label for="ca1">NO</label>
</div>
/* php post update */
$radioPost="INSERT INTO questions
( ca1y,
ca1s,
ca1n,...)
VALUES
( '$_POST[ca1y]',
'$_POST[ca1s]',
'$_POST[ca1n]',...)
I tried to give each radio button an ID attribute and use that to update the database but I can't seem to get that to work....
any help would be greatly appreciated
cheers.
I'm not sure if I'm getting the jist of what you trying to do, but it seems like you need to save an individuals answers to different questions to the DB but that each question can only have ONE of let's say three possible answers. Well, in that case you might think of redesigning your DB to look something like this:
You store the users details in the users table, the question details in the questions table and the different answers in the answers table. A user will be able to answer multiple questions but can only answer a particular question once. You then save the answer in ONE field called answer_value for example. There is no need to store the answer in multiple fields since you will be storing the VALUE of the radio button they chose, i.e you will store either a 10, 5 or -10 depending on which radio option was selected.
It's also important that in your HTML you name all the radio buttons for a particular question the same. This ensures that the radio options act as radio buttons and not as checkboxes. Your HTML would most likely look something like this:
<div class="questionBox">
<p>1.Have I clearly defined my companies target market?</p>
<input type="radio" name="q1" value="10"/>
<label for="ca1">YES</label>
<input type="radio" name="q1" value="5"/>
<label for="ca1">SOMEWHAT</label>
<input type="radio" name="q1" value="-10"/>
<label for="ca1">NO</label>
</div>
<div class="questionBox">
<p>2.Have I clearly defined my companies product?</p>
<input type="radio" name="q2" value="10"/>
<label for="ca2">YES</label>
<input type="radio" name="q2" value="5"/>
<label for="ca2">SOMEWHAT</label>
<input type="radio" name="q2" value="-10"/>
<label for="ca2">NO</label>
</div>
.....
Note that question 1 has 3 radio options all named "q1" and question 2 has 3 radio options all named "q2". Follow the same convention for all your questions. Your PHP then becomes pretty straightforward and will probably look something like this:
$radioPost="INSERT INTO answers (user_name, question_name, answer_value)
VALUES (('$_POST[user_name]', 'q1', '$_POST[q1]),('$_POST[user_name]', 'q2', '$_POST[q2]), ....)
If you not sure what the radio button names are, you can use a foreach loop as follows:
$user = $_POST[user_name];
foreach ( $_POST as $key => $val )
{
If ($key <> 'user_name') //you might need to check that you only reading the radio options
{
$radioPost="INSERT INTO answers (user_name, question_name, answer_value)
VALUES ('$user', $key, '$val')"
....
}
}
Also be advised that even if you only using radio options, you should still clean the inputs to prevent attacks like SQL-Injection etc. I suggest you find some more info on securing your code against attack.
BTW, if you place the questions in a table of it's own, you can dynamically create your questionnaire from this table, which then allows you to add or delete questions at will, making your whole application a lot more flexible. And saving your answers in one field instead of three, will remove all the NULL values from your table, which will simplify your queries when you perform calculations. I know MySQL normally puts a zero as the default integer value, but it's still better to save it into one field. If you want to know which option a user chose for a particular question, just check the value stored in that field.
Not very good solution: write js to deselect appropriate radio buttons.
On more serious note i don't understand the need to have all radios with different names. Why is such solution not applicable: name radios in one question with same name, lets say question1, then after form post just look at value and from that you can easily update db. I suppose you want to collect how many times each radio was selected. So if you know that question1 had choice 1 you than also know that question1 did not have choices 2 and 3. Unless you collect data in other way or for other purpose, but then I think there need to be a bit more input from you about the purpose of this. Though I still think you can do this like i said, this would not need complex processing, id say rudimentary programming knowledge should suffice.
the site i'll be refering to is
http://www.iaddesignandstudio.com/offline select the quote tab
if a person where to fill out this form and select more than one checkbox in either number 1 or number 3. how would i insert those selected values into a database so that when i retreive the information the user inputed or selected i can see which checkboxes he/she selected?
You can set your checkboxes to be in one array after the form is submitted by adding [] at the end of the name attribute like such:
<input type="checkbox" name="services[]" value="Podcasting Services" />
Podcasting Services
<input type="checkbox" name="services[]" value="Local Search" />Local Search
When the form is submitted, your $_POST['services'] variable will be an array containing all checked values. ex:
#var_dump($_POST['services']);
array(2) {
[0]=>
string(19) "Podcasting Services"
[1]=>
string(12) "Local Search"
}
Then you can do anything you want with that, wether it be sending an email or adding fields to the database using ether foreach() or implode() to loop through the values.
Hope this helps!
I would have separate fields in the database for them. Like in question 1, the posted form might submit $_POST['admycomp'] and $_POST['provideresource'] as having been checked. If so, insert a 1 into the database field admycomp or provideresource. That way you have recorded which fields they checked.
I would suggest storing the values in your database would be to use the SET datatype (eg: http://dev.mysql.com/doc/refman/5.0/en/set.html). This would store each of the checkbox values from a checkbox group in a single column in a storage-efficient way. You would probably need to use implode as mentioned above to create an SQL query to insert your set.