如何缩短这部分代码?

时间:2019-04-15 14:10:28

标签: php mysql html5

我只知道这部分代码对性能Web应用程序不好,因为它在执行过程中花费了很多时间而不是一个,而是两个SQL查询。我想阅读您对这部分代码的建议。另外,我想阅读您的代码解决方案。代码可以正常工作。

感谢您的帮助。

提前谢谢

<html>
<body>
    <select name="category">
        <option value="category">category name</option>
        <?php
        $sql = "SELECT category.name as cat, article.name as art from category
        JOIN article ON category.id = article.id";
        $query = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_array($query)){
        echo "
        <option value='".$row["cat"]."'>".$row["cat"]."</option>";
        }
        mysqli_close($conn);
        ?>
    </select>
    <select name="article">
        <option value="articlename">article name</option>
        <?php
        $sql = "SELECT category.name as cat, article.name as art from category
        JOIN article ON category.id = article.id";
        $query = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_array($query)){
        echo "
        <option value='".$row["art"]."'>".$row["art"]."</option>";
        }
        mysqli_close($conn);
        ?>
    </select>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您无需与数据库建立2个连接即可获取相同的数据。您可以创建对象的集合,并在类似的地方使用它们。

<?php
  $arr = [];

  $sql = "SELECT category.name as cat, article.name as art from category 
  JOIN article ON category.id = article.id";

  $query = mysqli_query($conn, $sql);

  while($row = mysqli_fetch_array($query)){
      $obj = (object) [
          "cat" => $row["cat"],
          "art" => $row["art"]
      ];

      array_push($arr, $obj);
  }

  mysqli_close($conn);
?>

<select name="category">
<option value="category">category name</option>
foreach($arr as $obj) {
    ?>
        <option value='"<?php echo $obj->cat; ?>"'><?php echo $obj->cat; ?></option>
    <?php
}

<select name="article">
<option value="articlename">article name</option>
foreach($arr as $obj) {
    ?>
        <option value='"<?php echo $obj->art; ?>"'><?php echo $obj->art; ?></option>
    <?php
}

答案 1 :(得分:0)

您可以准备将​​<option>保留在一个循环中的字符串,然后简单地回显它们。

例如:

<?php
$sql = "SELECT category.name as cat,
               article.name as art
        FROM category 
        JOIN article
        ON category.id = article.id";
$query = mysqli_query($conn, $sql);
$articles = "";
$categories = "";
while($row = mysqli_fetch_array($query)) {
    $categories .= "<option value='" . $row["cat"] . "'>" . $row["cat"] . "</option>";
    $articles .= "<option value='" . $row["art"] . "'>" . $row["art"] . "</option>";
}
mysqli_close($conn);
?>
<select name="category">
    <option value="category">category name</option>
    <?php echo $categories; ?>
</select>
<select name="article">
    <option value="articlename">article name</option>
    <?php echo $articles; ?>
</select>