duanju8431 2014-04-03 07:48
浏览 28
已采纳

PHP SELECT循环

I have a School database with two courses, each course has 12 possible subject fields (co_subj...) that can contain the subject ID or NULL, in this case course ID 1 has 3 subjects, and course 2 has only 1:

Courses

I need PHP to create a <div> for each subject found on a course, and don't create nothing in any NULL case. Querys:

$select = mysql_query("SELECT * FROM course_conf JOIN course_type ON ct_id=co_fk_ct_id ORDER BY co_name");

And then a while makes PHP check every course's field:

while($registroBbdd = mysql_fetch_array($select))
                {
                    $class="";
                    $courseId=$registroBbdd['co_id'];
                    $courseName=$registroBbdd['co_name'];
                    $courseType=$registroBbdd['ct_name'];

The doubt comes right now, trying to solve the most efficient way the <div> creating I mentioned before. The only way I find to solve this is creating a conditional "IF" structure printing the if a value is found, and nothing if NULL is found, like this:

if($registroBbdd['co_subj1'] != NULL){
     echo "<div>'.$registroBbdd['co_subj1'].'</div>}
else if ($registroBbdd['co_subj2'] != NULL){
     echo "<div>'.$registroBbdd['co_subj2'].'</div>}
.............}

Is there any looping way to make this? In order to avoid the whole "if" structure creation.

  • 写回答

2条回答 默认 最新

  • douzhan8395 2014-04-03 07:54
    关注

    You could have the SQL statement do the work. For example:

    SELECT *, (CASE WHEN co_subj1 IS NOT NULL THEN co_subj1 ELSE co_subj2 END) AS subject 
    FROM course_conf JOIN course_type ON ct_id=co_fk_ct_id ORDER BY co_name
    WHERE co_subj1 IS NOT NULL OR co_subj2 IS NOT NULL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部