我的if语句未按预期运行

时间:2018-09-25 18:42:13

标签: php database if-statement foreach echo

如果entry_type是页面的entry_typepost,此代码将根据我在pagina列上有多少数据来复制元标记我在。而且它正在从metaif上打印else标签。

$mt = $conn->query("SELECT entry_type FROM bn_publicacao")->fetchAll();

foreach ($mt as $FB) {

    if ($FB['entry_type'] == 'pagina'){ 
        echo '<meta property="og:type" content="website">';
    } else{
        echo '<meta property="og:type" content="article">';
        echo '<meta property="article:author" content="">';
        echo '<meta property="article:publisher" content="">';
        echo '<meta property="article:published_time" content="">';
        echo '<meta property="article:modified_time" content="">';
    }

 }

编辑:我解决了重复项的问题

$mt = $conn->query("SELECT entry_type FROM bn_publicacao WHERE entry_type IS NOT NULL GROUP BY entry_type")->fetchAll();

foreach ($mt as $FB) {

    if ($FB['entry_type'] == 'pagina'){ 
        echo '<meta property="og:type" content="website">';
    } else{
        echo '<meta property="og:type" content="article">';
        echo '<meta property="article:author" content="">';
        echo '<meta property="article:publisher" content="">';
        echo '<meta property="article:published_time" content="">';
        echo '<meta property="article:modified_time" content="">';
    }

 }

但是我仍然遇到ifelse同时打印的问题。

print_r的结果:

$mt = $conn->query("SELECT entry_type FROM bn_publicacao WHERE entry_type IS NOT NULL GROUP BY entry_type")->fetchAll();

foreach ($mt as $FB) {
print_r($mt); //Result 1

    if ($FB['entry_type'] == 'pagina'){
    print_r($mt); //Result 2

        //code posted on the question

    } else{    
      print_r($mt); //Result 3

        //code posted on the question

    }

}
  • 结果1:
  

Array([0] => Array([entry_type] => pagina [0] => pagina)[1] => Array([entry_type] => post [0] => post))Array([0 ] =>数组([entry_type] => pagina [0] => pagina)[1] =>数组([entry_type] => post [0] => post))

  • 结果2:
  

Array([0] => Array([entry_type] => pagina [0] => pagina)[1] => Array([entry_type] => post [0] => post))

  • 结果3:
  

Array([0] => Array([entry_type] => pagina [0] => pagina)[1] => Array([entry_type] => post [0] => post))

我的代码有什么问题?而我该如何解决呢?

1 个答案:

答案 0 :(得分:1)

fetchColumn仅返回一个结果,fetchColumn。您可以使用fetchAll将所有结果作为数组返回。

您需要遍历结果,因为它将是一个数组。下面的代码:

$mtFBs = $conn->query("SELECT entry_type FROM bn_publicacao")->fetchAll();
foreach ($mtFbs as $mtFb) {
   if ($mtFB['entry_type'] == 'pagina'){ 
     echo '<meta property="og:type" content="website">';
   } else{
      echo '<meta property="og:type" content="article">';
      echo '<meta property="article:author" content="">';
      echo '<meta property="article:publisher" content="">';
      echo '<meta property="article:published_time" content="">';
      echo '<meta property="article:modified_time" content="">';
   }
 }