仅函数 returns 一个值多次

function only returns one value multiple times

我有这个function:

function get_content($text_to_match) {
    $query  = "SELECT * ";
    $query .= "FROM table_name ";
    $query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
    $cont = mysqli_query($connection, $query);
    if($content = mysqli_fetch_assoc($cont)) {
        return $content;
    } else {
        return null;
    }
}

但是当我这样称呼它时:

  <div>
      <?php
        for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
          echo '<article>' .
                 '<h3>' . get_content("text_to_match")["string1"] . '</h3>'.
                 '<p>' . get_content("text_to_match")["string2"] . '</p>' .
               '</article>';
        }
      ?>
  </div>

我只得到 DB 中的第一个匹配项,重复次数与找到的项数一样多。

我哪里做错了?

使用此代码然后正确获取数据

 while($content = mysql_fetch_array($cont))
{
   return $content;

 }

你的逻辑有问题。您正在调用 get_content 函数来获取循环的所有匹配项,以及从列表中获取单个元素。这是:

  • 错误的逻辑 - 第二个用例没有意义
  • 过度 - 你不应该 运行 数据库查询只是为了输出一个已经检索到的结果

您可能想要做的是:

foreach (get_content('text_to_match') as $content) {
    echo '<article>';
    echo '<h3>' . $content['string1']  . '</h3>';
    echo '<p>' . $content['string2'] . '</p>';
    echo '</article>';
}

结合@Anant 和@Unix One 的回答中的提示进行一些修改,我得出了这个可行的解决方案:

函数定义

  function get_content($text_to_match, $multiple=false) {
        $query  = "SELECT * ";
        $query .= "FROM table_name ";
        $query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
        $cont = mysqli_query($connection, $query);
        if ($multiple) {
          $content_array = [];
          while($content = mysqli_fetch_array($cont)) {
            $content_array[] = $content;
          }
          return $content_array;
        } else {
          if($content = mysqli_fetch_assoc($cont)) {
            return $content;
          } else {
            return null;
          }
        }
   }

函数调用

<?php
  /* multiple items */
  foreach(get_content("text_to_match", true) as $content) {
    echo '<article>' .
           '<h3>' . $content["string1"] . '</h3>' .
           '<p>' . $content["string2"] . '</p>' .
         '</article>';
  }
?>

<?php
  /* one item */
  echo get_content("text_to_match")["string"];
?>