$_POST Info
I have a web site I'm creating for a used car dealer. I currently have one table (Car) in the db for info regarding each specific car (VIN, Make, Model, Price, etc.). I have another table (Features) that is a generic list of possible features any car might have (# airbags, type of fuel, sound/stereo components, type of seats, etc.). I also have an association table (Car-Features) linking the car table to the appropriate features in the Features table.
The Features table won't contain any info specific to any given car. I use it merely to dynamically create check boxes for adding/editing car info. (I will be creating an administrative form for the site administrator to add/delete features to/from this table.) In order to keep the code dynamic, I'm not sure how to dynamically assign the form fields to variables for inserting the data into the Car/Car-Feature tables. Currently I have the $_POST data hard coded to variables. I'm getting myself so confused, I'm not even sure I'm asking the question coherently.
Can anyone give me some advice?
TIA,
teammatt3 posted this at 00:27 — 10th September 2010.
He has: 2,102 posts
Joined: Sep 2003
You would loop through your features table, and generate all the checkboxes:
<input type="checkbox" name="features[1]" value="1" />4 wheel drive
<input type="checkbox" name="features[2]" value="1" />Power steering
<input type="checkbox" name="features[3]" value="1" />ABS
...
Notice that the primary key of your features table is inside the brackets of the input name.
When that form is submitted, you'll get $_POST['features'] that is, itself, an array of all the form elements that were checked. So you would loop through them, and insert them into your Car-Features table:
<?php
$car_id = (int)$_POST['car_id'];
// delete all the old features
query("DELETE FROM CarFeatures WHERE car_id = $car_id");
// loop through all the new features, and insert
foreach($_POST['features'] as $feature_id => $v){
$feature_id = (int)$feature_id;
$sql = "INSERT INTO CarFeatures(car_id, feature_id) VALUES($car_id, $feature_id)";
query($sql);
}
?>
Does that help?
Dami posted this at 01:47 — 10th September 2010.
She has: 88 posts
Joined: Sep 2001
Yeah, that does give me a jumping off place. I was having a time figuring out how to insert the selected features into the association table. This is very helpful.
Thanks so very much!
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.