如何在 php 代码中从数据库的第一行检索数据


How to retrieve data from the first row from database in php code

我写这段代码是为了从数据库中检索一些数据,但是代码不显示从第二行开始的表中的第一个值。我如何使此代码从第一行检索数据。

<html>
<head>
<title>hello</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");  
$q = " SELECT * FROM student_record WHERE id =201102887;";
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result)) {
    echo "<table border='"1'" style='"width:500'">";
    echo "<tr>";
    echo "<th>courses</th>";
    echo "</tr>";
    while($row = mysqli_fetch_array($result))
    {
       echo "<tr>";
       echo "<td>" . $row["grade"]. "</td>";
       echo "</tr>";
    }
    echo "</table>";
}   
?>
</body>
</html>

更改

if($row = mysqli_fetch_array($result)) {

if(mysqli_num_rows($result) > 0) {

更新的代码

<html>
<head>
<title>hello</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");  
$q = " SELECT * FROM student_record WHERE id =201102887;";
$result = mysqli_query($con , $q ) ;
if(mysqli_num_rows($result)>0) {
    echo "<table border='"1'" style='"width:500'">";
          echo "<tr>";
            echo "<th>courses</th>";
          echo "</tr>";
          while($row = mysqli_fetch_array($result))
          {
             echo "<tr>";
                echo "<td>" . $row["grade"]. "</td>";
             echo "</tr>";
          }
    echo "</table>";
}   
?>
</body>
</html>

我所知,当你两次调用它时,

if($row = mysqli_fetch_array($result)) {

那么当你在循环中再次调用它时,第一行会跳过,你if($row = mysqli_fetch_array($result)) {创建什么点? 如果你只想检查查询返回,你可以使用if($result) {

您正在呼叫mysqli_fetch_array两次,第二次调用将转到第二行。像这样尝试

<html>
<head>
<title>hello</title>
</head>
<body>
<?php
  $con = mysqli_connect('localhost', 'root', '');
  mysqli_select_db($con,"uoh");  
  $q = " SELECT * FROM student_record WHERE id =201102887;";
  $result = mysqli_query($con , $q ) ;
  $rows = array();
  while($row = mysqli_fetch_array($result))
  {
    $rows[] = $row;
  }
  if(count($rows) > 0) {
      echo "<table border='"1'" style='"width:500'">";
      echo "<tr>";
      echo "<th>courses</th>";
      echo "</tr>";
      foreach($rows as $row)
      {
         echo "<tr>";
         echo "<td>" . $row["grade"]. "</td>";
         echo "</tr>";
      }
      echo "</table>";
  }   
?>
</body>
</html>