回应数据库

时间:2017-11-18 09:38:17

标签: php mysql mysqli

我有一些PHP代码可以从数据库中设置变量。我会解释一下,如果没有意义,请告诉我。

因此,如果*,我有一个查询从表格中选择class = '$class'。这一切都有效我开始工作了。

然后我设置了像$id = $row["id"];这样的变量,并且一切正常,在我的HTML代码中我有<p><?php echo $id?></p>,如果它们class = $class它会显示它,但是,如果它没有满足那些没有设置变量的要求,所以我得到错误Notice: Undefined variable: id in C:\wamp64\www\studentplanner\account\homework.php on line 73

我想要做的只是在满足要求的情况下以HTML格式输出结果。

不知道这是否有意义!

$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
      $id = $row["id"];
      $teacher_set = $row["teacher_set"];
      $class = $row["class"];
      $name = $row["name"];
      $description = $row["description"];

    }
}


          <p><?php echo $id?></p>
          <p><?php echo $teacher_set?></p>
          <p><?php echo $class?></p>
          <p><?php echo $name?></p>
          <p><?php echo $description?></p>

2 个答案:

答案 0 :(得分:1)

在while循环之前设置标志变量然后使用该变量来决定是否以html打印数据

$data_exist = false;
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    $data_exist = true; 
    while($row = mysqli_fetch_assoc($result)) {
      $id = $row["id"];
      $teacher_set = $row["teacher_set"];
      $class = $row["class"];
      $name = $row["name"];
      $description = $row["description"];

    }
}


if($data_exist)
{
?>

          <p><?php echo $id?></p>
          <p><?php echo $teacher_set?></p>
          <p><?php echo $class?></p>
          <p><?php echo $name?></p>
          <p><?php echo $description?></p>
<?php
} 
?>

答案 1 :(得分:0)

 $sql = "SELECT * FROM homework WHERE class = '$class'";
 $result = mysqli_query($conn, $sql);

 if (mysqli_num_rows($result) > 0) {
 while($row = mysqli_fetch_assoc($result)) { 
 ?>  
    <p><?php echo $row["id"];?></p>
    <p><?php echo $row["teacher_set"];?></p>
    <p><?php echo $row["class"];?></p>
    <p><?php echo $row["name"];?></p>
    <p><?php echo $row["description"];?></p>
<?php } } ?>