My result is spitting out a duplicate of each record as opposed to a unique foreach match. As you can see I am trying to loop through and get each unique value WHERE $s=id.. I know the query needs to be within the while(),
The array $seminar being passed from checkboxes on my form.
if ($seminar) {
foreach ($seminar as $s)
$interest .= "$s ";
}
NOTE: The $interest is what I am using to insert into my table (it's not part of this problem)
For array data, this is what is being returned by $seminar
Array
(
[0] =>开发者_C百科; 1
[1] => 8
[2] => 9
[3] => 10
[4] => 13
)
Here is my code:
$query_seminars = mysql_query("SELECT id, name, UNIX_TIMESTAMP(moment) FROM seminars WHERE id={$s}");
while ($sem_row = mysql_fetch_assoc($query_seminars))
{
$names .= "-- " . $sem_row['id'] . " " . $sem_row['name'] . date('D, F j, Y, g:i a', $sem_row['moment']) . "<br />";
}
You do not need the foreach in the while loop, here:
$query_seminars = mysql_query("SELECT id, name, UNIX_TIMESTAMP(moment) FROM seminars WHERE id={$s}");
while ($sem_row = mysql_fetch_assoc($query_seminars))
{
$names .= "-- " . $sem_row['id'] . " " . $sem_row['name'] . date('D, F j, Y, g:i a', $sem_row['moment']) . "<br />";
}
Also to use named indexes you use mysql_fetch_assoc
, not mysql_fetch_array
. (Already in above code)
The problem is not that MySql is returning duplicate (actualy tri-plicate) items. The problem is that you are iterating over each record with your foreach
, as others pointed out.
One usual idiom used with MySql is:
$sql = "SELECT id, name, UNIX_TIMESTAMP(moment) FROM seminars WHERE $s=id";
if ($q = mysql_query($sql)) {
while ($f = mysql_fetch_assoc($q)) {
//($f is an associative array of the record value,
//with keys for each field)
//... do something with $f
echo "--" . htmlspecialchars($f['name'])
. date('D, F j, Y, g:i a', $f['moment'])
. "<br /><br />";
}
} elseif ($e = mysql_error()) {
//do something with the error message
//...
}
You are seeing "duplicates" because you are using a foreach
inside the while loop to iterate by each field of the returned record. Since your query is returning records with three fields each (id, name and moment), you are processing each record three times.
精彩评论