如何在php中显示所有行

时间:2016-03-13 18:53:21

标签: php mysql mysqli

我编写了这段代码来检索数据库中的某些行

session_start();
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
    die("not ok");
}

mysqli_select_db($con,"uoh");  

$q = " SELECT * FROM student WHERE id = " . $_SESSION['user_id'] ." and password = " . $_SESSION['user_pass'];
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result))
{
   echo "this academic transcripts for " . $row["name"];
   echo " and the id is " . $row["id"];

}

$q1 = " SELECT student_record.course,student_record.grade,student_record.term,coe_courses.crd 
    FROM student_record INNER JOIN coe_courses ON student_record.course_number = coe_courses.course_number 
    where student_record.id = ".$_SESSION['user_id'] ;
$result = mysqli_query($con , $q1 ) ;
if($row = mysqli_fetch_array($result))
{
   echo "<br />";
   echo "<table border=\"1\" style=\"width:500\">";
   echo "<tr>";
   echo "<th>coe_courses</th>";
   echo "<th>terms</th>";
   echo "<th>Grades</th>";
   echo "<th>CRD</th>";
   echo "</tr>";
   echo "<tr>";
   echo "<td>" . $row["course"]. "</td>";
   echo "<td>" . $row["term"]. "</td>";
   echo "<td>" . $row["grade"]. "</td>";
   echo "<td>" . $row["crd"]. "</td>";
   echo "</tr>";
   echo "</table>";
}

问题是只显示第一行,而我在phpMyAdmin中有三行。 enter image description here

1 个答案:

答案 0 :(得分:2)

您需要重复调​​用fetch_* 以检索结果集中的所有行;每次调用它时,它都会检索结果集中的 next 行。

在上面的示例代码中,您将替换

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

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

这将循环直到fetch_array尝试读取$result中的最后一条记录,此时fetch_array返回 false 和循环退出。