我目前在MySQL数据库中有5个表。它们中的一些共享外键并且彼此相互依赖。我正在向他们的专业展示相应的课程。每个课程都在fall
,spring
或all_year
期间授课。在我的数据库中,我有一个名为semester的表,其中包含id
,year
和semester
字段。 semester
字段特别是tinyint
,其中包含三个值0
,1
,2
。这表示fall
,spring
或all_year
。当我显示查询而不是显示0
或1
或2
时,我是否可以显示fall
,spring
等?额外:如何在每个循环的末尾添加空格,以便数据看起来不会聚集?
关键
0 Fall
1 Spring
2 All-year
PHP
<?
try {
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("SELECT course.name, course.code, course.description, course.hours, semester.semester, semester.year
FROM course
LEFT JOIN major_course_xref ON course.id = major_course_xref.course_id
LEFT JOIN major ON major.id = major_course_xref.major_id
LEFT JOIN course_semester_xref ON course.id = course_semester_xref.course_id
LEFT JOIN semester ON course_semester_xref.semester_id = semester.id");
$query->execute();
if ($query->execute()){
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
print $row['name'] . "<br>";
print $row['code'] . "<br>";
print $row['description'] . "<br>";
print $row['hours'] . " hrs.<br>";
print $row['semester'] . "<br>";
print $row['year'] . "<br>";
}
}
else
echo 'Could not fetch results.';
unset($pdo);
unset($query);
?>
当前显示
Computer Programming I
CPSC1400
Introduction to disciplined, object-oriented program development.
4 hrs.
0
2013
欲望展示
Computer Programming I
CPSC1400
Introduction to disciplined, object-oriented program development.
4 hrs.
Fall
2013
答案 0 :(得分:1)
将查询中的semester.semester
替换为:
CASE semester.semester
WHEN 0 THEN 'Spring'
WHEN 1 THEN 'Fall'
WHEN 2 THEN 'All-year'
END semester
答案 1 :(得分:1)
制作另一张桌子。说semester_time。
| id | semester_time |
| 0 | Fall |
| 1 | Spring |
| 2 | All_year |
然后在semester_time进行连接和后退。
基于上表的查询的可能模型:
SELECT course.name, course.code, course.description, course.hours, semester.semester, semester.year, semester_time
FROM course
LEFT JOIN major_course_xref ON course.id = major_course_xref.course_id
LEFT JOIN major ON major.id = major_course_xref.major_id
LEFT JOIN course_semester_xref ON course.id = course_semester_xref.course_id
LEFT JOIN semester ON course_semester_xref.semester_id = semester.id
LEFT JOIN semester_time ON semester.semester = semester_time.id
在每个循环后添加空格
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
print $row['name'] . "<br>";
print $row['code'] . "<br>";
print $row['description'] . "<br>";
print $row['hours'] . " hrs.<br>";
print $row['semester'] . "<br>";
print $row['year'] . "<br>";
echo "<div class='add-space'></div>";
}
在css中
.add-space {
margin-bottom: 15px;
}
只需更改值即可满足您的需求。
答案 2 :(得分:0)
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
print $row['name'] . "<br>";
print $row['code'] . "<br>";
print $row['description'] . "<br>";
print $row['hours'] . " hrs.<br>";
print ($row['semester'] == 0) ? "FALL":( ($row['semester'] == 1) ? "Spring" : ( ($row['semester'] == 2) ? "All-year":"")) . "<br>";
print $row['year'] . "<br>";
print "<br>------------------------------<br />";
}