PHP中没有从SQL数据表中显示所有值

时间:2019-07-12 08:33:53

标签: php mysql sql

我正尝试像下面这样显示从MySQL到PHP的所有数据,但仅显示1个数据

<div class="content">
<div class="animated fadeIn">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<strong class="card-title">Data Table</strong>
  </div>
<div class="card-body">

<?php

// Attempt select query execution
$sql = "SELECT * FROM registers";
if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $test= $row['id'];
        }
        // Free result set
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
?>
<table id="bootstrap-data-table" class="table table-striped table-bordered">
  <thead>
  <tr>
    <th>Name</th>
  <th>Position</th>
  <th>Office</th>
    <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
    <td><?php echo $test; ?></td>
  <td><?php echo $name?></td>
  <td><?php echo $email?></td>
  <td><?php echo $company?></td>
  </tr>

  </tbody>
  </table>
  </div>
    </div>
    </div>

现在的问题是,表中仅显示一个数据,如何用相同的代码显示所有数据?谁能告诉我吗?

2 个答案:

答案 0 :(得分:2)

<?php

  // Attempt select query execution
   $sql = "SELECT * FROM registers";
  $test=array();
  if($result = mysqli_query($link, $sql)){
         if(mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_array($result)){

                      array_push($test,$row);
                }
           // Free result set
             mysqli_free_result($result);
            } else{
               echo "No records matching your query were found.";
        }
     } else{
         echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
     }

在视图部分,您添加了foreach以打印所有值:

<?php 
foreach($test as $record){?>
 <tr>
    <td><?php echo $test['id']; ?></td>
  <td><?php echo $test['name'];?></td>
  <td><?php echo $test['email'];?></td>
  <td><?php echo $test['company']?></td>
  </tr>
<?php } ?>

答案 1 :(得分:0)

您的代码有两个问题,您似乎从未设置过$ name,$ email和$ company变量,并且遍历了数组并在循环后设置了HTML,因此,您只会显示一个结果。

即将进行编辑。

_f