簡體   English   中英

如何在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>

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

據我所知,當你打電話兩次時,

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

那么當您在循環中再次調用它時,第一行將跳過,您創建if($row = mysqli_fetch_array($result)) {什么? 如果您只想檢查查詢返回,您可以使用if($result) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM