I've already posted this but I want to explain it better. I have a website in which students insert their 4 courses and 4 comments for each course, these are the SQL table columns: Course1, Course2, Course 3, Course 4, Comment1, Comment2, Comment 3, Comment 4.
I have a search in which any student inputs, for instance, geography (which may be saved in any of the four course columns), and I want my SQL query to return all the comments for geography. For example, if a student saved Geography in position Course2, I want my SQL query to select comment2 where course2 = geography. He may have saved it in course1, so it has to be flexible, but only select the course chosen by the student. This is my current SQL query:
$SQL = "SELECT (Comment1 FROM Students WHERE Course1 = 'geography'), (Comment2 FROM Students WHERE Course2 = 'geography'), (Comment3 FROM Students WHERE Course3 = 'geography'), (Comment4 FROM Students WHERE Course4 = 'geography')";
Currently, this SQL query isn't working. I know the structure may seem odd, but logically, as you may understand, this makes sense, though it's probably not the right way to code it. I then print all the geography comments like this:
$null = '';
if(mysql_num_rows($result)) {
echo "<ol>";
while ($row=mysql_fetch_array($result)) {
if($row["Class"]!=$null) {
if($null!='') {
echo "</ol><ol type='1'>";
}
}
echo "<li><p>" . " " . $row["Comment1"]. " " . $row["Comment2"]." " . $row["Comment3"] . " " . $row["Comment4"] . "</li></p>";
$i = $i +1;
}
echo "</ol>";
Your query is wrong: Try this
SELECT Comment1, Comment2, Comment3, Comment4
FROM Students
WHERE Course1 = '$value1' AND Course2 = '$value1'
AND Course3 = '$value1' AND Course4 = '$value1'
OR
SELECT Comment1, Comment2, Comment3, Comment4
FROM Students
WHERE Course1 = '$value1' OR Course2 = '$value1'
OR Course3 = '$value1' OR Course4 = '$value1'
Based on your requirement use AND or OR while checking course
I am not sure that I have understood what you want but you can try this (untested):
SELECT Student_ID,
CASE
WHEN Course1 = 'geography' THEN Comment1
ELSE NULL
END AS comment1_result,
CASE
WHEN Course2 = 'geography' THEN Comment2
ELSE NULL
END AS comment2_result,
CASE
WHEN Course3 = 'geography' THEN Comment3
ELSE NULL
END AS comment3_result,
CASE
WHEN Course4 = 'geography' THEN Comment4
ELSE NULL
END AS comment4_result
FROM Students
Assuming that table structure really(sic) can't be changed (anymore) I'd go with a UNION here
( SELECT Comment1 as comment FROM soFoo WHERE Course1='geography' )
UNION ALL
( SELECT Comment2 as comment FROM soFoo WHERE Course2='geography' )
UNION ALL
( SELECT Comment3 as comment FROM soFoo WHERE Course3='geography' )
UNION ALL
( SELECT Comment4 as comment FROM soFoo WHERE Course4='geography' )
It gives MySQL at least a fighting chance to use indices to find the matching records.