简体   繁体   中英

How do I display the same MySQL query twice using PHP?

I selected values from my table, and wanted to display them two separate times. In the first instance, I wanted to display all cells in a table, and this works. In the second instance, I wanted to make a drop down from one of the columns. Only the first one works; how can I get both to work? I also need all of the rows in the table to display, which is why I thought a while loop was a good idea. But please correct me if I'm wrong in my thinking. Thanks.

<!DOCTYPE html>
<?php

$host = "localhost";
$username = "redacted";
$password = "redacted";
$db = "redacted";

$connection = mysqli_connect($host, $username, $password, $db);

if (mysqli_connect_errno()) {
  echo "Connection error";
}

$query = "SELECT * FROM main";

$result = $connection->query($query);

?>

<html>
  <head>
    <title>Test Page</title>
  </head>
  <body>
    <h1>Test Main Table Display</h1>
    <table>
      <?php
      // first instance
      while($row = mysqli_fetch_array($result)) {
        echo "<tr>";
        echo "<td>" . $row['user'] . "</td>";
        echo "<td>" . $row['date'] . "</td>";
        echo "<td>" . $row['count'] . "</td>";
        echo "<td>" . $row['action'] . "</td>";
        echo "<td><button>Expand</button></td>";
        echo "</tr>";
      }
      ?>
    </table>
    <h1>Test User Entry Appendment</h1>
    <form>
      <label>Select a user, or add a new user.</label><br>
      <select>
        <?php
        // second instance
        while($row = mysqli_fetch_array($result)) {
          echo "<option>" . $row['user'] . "</option>";
        }
        ?>
      </select>
    </form>
  </body>
</html>

add this line before second loop set the pointer back to the beginning

mysqli_data_seek($result, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM