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.
Related
I have a multi-screen form that potential clients can fill in their information for a loan. There are 3 dropdown boxes for financial ranges in increments of 25,000. There are also text boxes for personal information (name, email, etc.).
The data types for these 3 fields are varchar(45).
The form inserts the data into a MySQL table and the 3 financial fields are formatted correctly. For example, if a potential clients selects the value for 150,000, the field in the database shows 150,000.
We can then open up our CRM to update these leads to enter more data or modify data. If, for instance, we try to update a phone number or street address - not any of the financial fields, all 3 financial fields have their values missing the comma and 3 trailing zeros.
This is one of the fields in the edit form php file:
<input class='' type="text" class="lamount" id="input-id-1" style="width:100px;" value='' name="loan_amount">
This is how I am updating it:
$loan_amount = $_POST(number_format(['loan_amount']));
With the binding:
$stmt->bindParam(":loan_amount", $loan_amount);
Then, I update the values in the database. All values that have been updated are updated correctly, except for the 3 values that are the financial values that were originally inserted by the forms.
I didn't know how to give title to this but I have the following database:
accidentDetain(id, location, weather_conditions desc (and few more columns));
weatherConditions(id, title)
acc_weat_cond(id, wc_id, ad_id)
wc_id = weatherConditions ID, ad_id = accidentDetain ID
Now the situation is the user can store multiple weather conditions such as (rain, wet, snow Ice Fog etc)
Let's say user chooses 3 out of those 6 options and those will be stored in acc_weat_cond table, with accident Detail id and weather conditions id.
After saving, the user decided to change and to unchecked one of the option and then presses the save button. The issue is, there are 3 records already stored into acc_weat_cond table how would I would change and make them to two records.
Will I have to delete the first records from the database and then store again newly checked options? Or is there any easier way doing the above mentioned situation.
One last option is that I violate the role of database normalization and stored directly in the accidentDetails table and separate the values with a comma.
Feel free to ask if any more information is required...
I would have an <input type='hidden'name='checkedflds' value='1,2,3' />-field which contained the values that were checked before the user updated. Then after postback, you can compare the new list against this and will easily see what additions he made and which elements he removed...
I would call all of the options and compare to what is checked, and delete what you need. If you store it on the form, then there is a potential for out of date data.
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.
In my MySQL I have under the table used where I save the make, model, price of a car and there is a column named car_parts for the extras like gps system, air bags.
This column saves the values from many checkboxes in this format a value, b value, f value, g value.
In my page I have a search form, where the user select from dropdown menus some values (like model and price) and through checkboxes some car parts. As I said the car parts are saved in the column car_parts.
This is how I constructed my query, since I allow the user to submit the form with some values empty:
$conditions = array();
if (!empty($colour)) $conditions[] = "colour = '".mysql_real_escape_string($colour)."'";
...
...
...
$conditionString = "WHERE ".implode(' AND ', $conditions);
My thought is that I need to have the checkboxes with different names like
<input type="checkbox" name="cruisecontrol" value="Cruise Control"> Cruise Control
and make use of the $_POST["cruisecontrol"]; in the database.
My question is how can the Cruise Control or any others, to be checked if these values are contained into the car_parts a,d,Cruise Control,j,t,r values and construct the query?
Depends how you're storing the information in the car_parts field. But I think the LIKE clause may be your friend here. Say the user checked 2 boxes these will be set in your post array. I would have the check boxes an array of post values like
<input type="checkbox" name="options[]" value="cruisecontrol" />
<input type="checkbix" name="options[]" value="radio" />
Then you can grab the options values and use them in your query.. supposeing you want a car with all checked options and both options are checked...
$whereClause = "WHERE `car_parts` LIKE '%".implode("%' AND LIKE '%",$_POST[options])."%'"
should produce something like
WHERE `car_parts` LIKE '%cruisecontrol%' AND LIKE '%radio%'
This will return results where car_parts contains both cruise control and radio.
Hope that helps. Also don't forget to sanitize the data before feeding it to your query!
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>