Coruba67;10888271 wrote:Hi guys,
Am a little stuck on the concept of how to do a couple of things...
First up - if I use a multiple select box, and someone actually selects multiple options, how do I loop through the values that they have selected once the form has been submitted...
Append array brackets to the input name attribute in your html source code.
<select name="users[]" multiple>
<option>...
</select>
By doing that, $_POST['users'], in this example, becomes an array with the values for any users selected as array elements. Now you can just do a normal array loop to insert/update records.
Coruba67 wrote:
Secondly - and this is my tough one that I have been struggling with for a while - I am pulling a whole bunch of members from a table and displaying information... What I want to be able to do is allow a person coming to the webpage to update any detail on anyone and hit an update button once, then have all that information updating into the database.
Assuming you have a bunch of text boxes. One way is to make a hidden input field for each text input with the same value. When the user submits the changes, you can compare the text input values against the hidden values. Thus, you will only burden the database with real changes.
Coruba67 wrote:
The problem I am having is once the form is posted, how will I know how many results to expect and how do I define them all to then write relevant INSERT queries into the database?
Thanks in advance.
Well, at this point, you will be making UPDATE queries if folks are making changes, right? One strategy (and this goes along with the last suggestion) is to tag all your values with the primary key for the originating record at the same ordinal position. Thus, in the select menu above, "users[]" becomes "120_users[]" where 120 corresponds to the unique (auto incremented integer) primary id for that database record. Next, you just loop through the entire query. Here's some starter code as an example.
<?php
define('POST_KEY_SEARCHED', '_users');
foreach ($_POST as $key => $value) {
// only pay attention to one kind of value...
if ( substr($key, -( strlen(POST_KEY_SEARCHED) ) ) == POST_KEY_SEARCHED ) {
// extract primary key to work with by isolating number...
$current_id = str_replace(POST_KEY_SEARCHED, '', $key);
// Get record values back from form...
$firstname = $_POST[$current_id.'_firstname'];
$lastname = $_POST[$current_id.'_lastname'];
$age = $_POST[$current_id.'_age'];
// build query for just this record
$sql = "UPDATE table SET firstname = '$firstname', lastname = '$lastname', age = '$age' ";
$sql .= "WHERE primary_key = $current_id";
// todo: execute query...
}
}
?>