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

时间:2016-03-19 06:58:41

标签: php html sql

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

<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>

3 个答案:

答案 0 :(得分:1)

更改

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>

答案 1 :(得分:0)

您正在调用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>

答案 2 :(得分:0)

据我所知,当你两次打电话时,

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

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