Click to See Complete Forum and Search --> : foreach question


$var
03-13-2007, 04:17 PM
i would like to use multiple select to create multiple entries to a table.

my select looks like this, and it displays industries to categorize an event:
<?

$q5 = 'SELECT * FROM hcw_industry ORDER BY Ind_Ttl ASC';
$resultq5 = mysql_query($q5) or die('Query Error');
$countq5 = mysql_num_rows($resultq5);
echo "<select name=\"eventInd_IndID[]\" id=\"eventInd_IndID[]\" size=\"12\" multiple=\"multiple\">";
for ($i =0; $rowq5 = mysql_fetch_assoc($resultq5); ++$i) {

$indID = $rowq5['Ind_ID'];
$indName = $rowq5['Ind_Ttl'];

echo "<option value=\"$indID\">$indName</option>";
}
echo "</select>";
?>


i know about implode(); but it doesn't seem like it would work the same here.
i feel there needs to be a foreach statement to write an INSERT statement per each selected value.
how would i use the loop to insert multiple entries into this table:

$q1 = "INSERT INTO hcw_eventsInd (
EventInd_EventID,
EventInd_IndID,
EventInd_IndSubID,
EventInd_EventDate)
VALUES (
'".$eventID."',
'".$_POST["eventInd_IndID"]."',
'".$_POST["eventInd_IndSubID"]."',
'".$eventDate."')";
$result = mysql_query($q1) or die (mysql_error());

NightShift58
03-13-2007, 04:50 PM
Form:<?php
$q5 = 'SELECT * FROM hcw_industry ORDER BY Ind_Ttl ASC';
$resultq5 = mysql_query($q5) or die("Query Error q5: $q5<br>" . mysql_error()));

echo "<select name=\"eventInd_IndID[]\" id=\"eventInd_IndID[]\" size=\"12\" multiple=\"multiple\">";
WHILE ($rowq5 = mysql_fetch_assoc($resultq5)) :
echo '<option value="' . $rowq5['Ind_ID'] . '>' . $rowq5['Ind_Ttl'] . '</option>';
ENDWHILE;
echo "</select>";
?>Action:<?php
$arrINS = array();
FOREACH ($_POST['eventInd_IndID'] AS $key => $val) :
$arrINS[] = "('$eventID','$val','" . $_POST['eventInd_IndSubID'][$key] . "','#eventDATE')";
ENDFOREACH;
$sqlINS = implode(",", $arrINS);
$q1 = "
INSERT INTO hcw_eventsInd
(EventInd_EventID, EventInd_IndID, EventInd_IndSubID, EventInd_EventDate)
VALUES $sqlINS
";
$result = mysql_query($q1) or die ("SQL Error q1: $$q1<br>" . mysql_error());
?>

$var
03-14-2007, 11:51 AM
this is perfectly exactly what i was looking for, but i find just 2 small errors.

for example, i multi-select 3 values. it writes 4 entries to the database.
the first 3 contain the right ID, however the 4th value returns an ID of 0.
also with this, the 4th value will be the only one to return the date.

for the other 3 values with the proper ID's the date is returned blank.

ID EID IID Date
22 35 1 0000-00-00
23 35 2 0000-00-00
24 35 0 2007-05-15

NightShift58
03-14-2007, 09:46 PM
I was one key off... This:$arrINS[] = "('$eventID','$val','" . $_POST['eventInd_IndSubID'][$key] . "','#eventDATE')";should be:$arrINS[] = "('$eventID','$val','" . $_POST['eventInd_IndSubID'][$key] . "','$eventDATE')"; and that should fix the date problem. Without seeing more code, I don't think I can tell you why an additional record is being inserted.