如果条目为空,如何显示不同的值

时间:2019-03-24 12:18:04

标签: php sql

我正在使用PHP和SQL。我想实现可以伪编码为的内容:

if the field 'pro_foto1' is not empty:
  show the value of the field 'pro_foto1'
else:
  if the field 'pro_thema' is 'Vrede en Mensenrechten':
    show '/afbeeldingen/vrede-en-mensenrechten.jpg'
  if the field 'pro_thema' is 'Samenleven in Nederland'
    show '/afbeeldingen/samenleven-in-nederland.jpg'
  and so on

哪些PHP代码可以允许我这样做?我的主要困难在于检测空白字段。

3 个答案:

答案 0 :(得分:0)

您是否只想在SQL查询中使用coalesce()

select coalesce(pro_foto1, pro_thema) as what_I_show

我不太清楚列中的内容,您可能想构造pro_thema返回值:

select coalesce(pro_foto1,
                concat('/afbeeldingen/', replace(lower(pro_thema), ' ', '-'),
               ) as what_I_show

答案 1 :(得分:0)

在PHP中,使用wordpress,您可以将数据行读取到关联数组$row中,然后使用类似以下的方法进行处理:

$results = $wpdb->get_results("SELECT * FROM haella_projecten_test WHERE pro_status = 'normaal'",
                              "ARRAY");
foreach ($results as $row) {
    if (!empty($row['pro_foto1'])) {
        $photo = $row['pro_foto1'];
    }
    else {
        switch ($row['pro_thema']) {
            case 'Vrede en Mensenrechten':
                $photo = '/afbeeldingen/vrede-en-mensenrechten.jpg';
                break;
            case 'Samenleven in Nederland':
                $photo = '/afbeeldingen/samenleven-in-nederland';
                break;
            // ... add as many entries as required
            default:
                // show default photo
                break;
        }
    }
}

答案 2 :(得分:0)

以下代码给出正确的输出。感谢您帮助我找到正确的方法:

     if(empty($r->pro_foto1)){
         if($r->pro_thema == "Geloof en Samenleving") {
             echo "/afbeeldingen/geloof-en-samenleving.jpg"; 
         }
         elseif($r->pro_thema == "Milieu en Duurzaamheid") {
             echo "/afbeeldingen/milieu-en-duurzaamheid.jpg"; 
         }
         elseif($r->pro_thema == "Samenleven in Nederland") {
             echo "/afbeeldingen/samenleven-in-nederland.jpg"; 
         }
         elseif($r->pro_thema == "Vrede en Mensenrechten") {
             echo "/afbeeldingen/vrede-en-mensenrechten.jpg"; 
         }
         elseif($r->pro_thema == "Overig") {
             echo "/afbeeldingen/overig.jpg"; 
         }
         elseif($r->pro_thema == "Kerstgift") {
             echo "/afbeeldingen/overig.jpg"; 
         }
         else {
             echo "/afbeeldingen/overig.jpg"; 
         }
     }
     else{
         echo "".$r->pro_foto1.""; 
     }