在这个MySQLi / PHP代码段上挣扎于可维护性

时间:2016-04-11 21:15:44

标签: php mysql mysqli

我有一段可行的代码,但它非常混乱。目标是从用户搜索中检索所有相关行。例如:如果用户搜索“Jo'”,它将检索John和Josh:

有效的代码:

if($_SERVER["REQUEST_METHOD"] == "POST") {
  $search = trim(filter_input(INPUT_POST,"user_search",FILTER_SANITIZE_SPECIAL_CHARS));
  $search = preg_replace("#[^0-9a-z]#i", "", $search);

  if(!isset($error_message)) {
    $query = $db->query("SELECT * FROM User WHERE U_Forename LIKE '%$search%'
                    OR U_Surname LIKE '%$search%' OR U_Team LIKE '%$search'
                    OR U_City LIKE '%$search%'");
  }
}

  <?php
          if ($query->num_rows == 0) {
            $output = "No results found!";
          } else {
            echo "<h2>Search results for: " . $search . "</h2>";
            while($row = $query->fetch_assoc()) {
              $id = $row['U_ID'];
              $firstname = $row['U_Forename'];
              $lastname = $row['U_Surname'];
              $team = $row['U_Team'];
              $city = $row['U_City'];
              echo "<div class='searchresults'>";
              echo "<p> Name: " . ucfirst($firstname) . " " . ucfirst($lastname) . "</p>";
               echo "<p> Favourite Team: " . ucfirst($team) . "</p>";
              echo "<p> Location: " . ucfirst($city) . "</p>";
              echo "<a class='lift' href='profile.php?=[$id]'>View Profile</a>";
              echo "<a class='lift' href='#'>Follow Driver</a>";
              echo "</div>";
            }
          }
          ?>

我尝试过:

function getSearchResults($search) {
  global $db;
  $searchArray = array();
  $query = $db->query("SELECT * FROM User WHERE U_Forename LIKE '%$search%'
                  OR U_Surname LIKE '%$search%' OR U_Team LIKE '%$search'
                  OR U_City LIKE '%$search%'");
  if ($query->num_rows == 0) {
    echo "No results found!";
  } else {
    while($row = $query->fetch_assoc()) {
      $searchArray['U_ID'] = $row['U_ID'];
      $searchArray['U_Forename'] = $row['U_Forename'];
      $searchArray['U_Surname'] = $row['U_Surname'];
      $searchArray['U_Team'] = $row['U_Team'];
      $searchArray['U_City'] = $row['U_City'];
    }
  }
  return $searchArray;
}

然而这不会起作用,因为fetch_assoc()的第一个结果只存储在$ searchArray中而没有其他内容!有没有人有什么建议?我不确定接下来会在哪里开始编码。

詹姆斯。

1 个答案:

答案 0 :(得分:2)

每次运行循环时都会覆盖数组。您需要创建一个数组数组,以便返回一个数组。下面,我简化了您的代码,将当前行追加到您要返回的数组中。然后,您可以对返回的数据执行foreach并显示您的代码

while($row = $query->fetch_assoc()) {
  $searchArray[] = $row;
}

另外,protip:将您的数据库连接器作为参数传递,并避免将其用作全局(这是另一种最佳实践)

function getSearchResults($search) {
   global $db;

变为

function getSearchResults($search, $db) {

最后但并非最不重要的是,没有你的函数回显事物(让你调用这个函数的层做到这一点)。相反,只返回一个空数组

if ($query->num_rows == 0) {
   return $searchArray;
}