2017-11-18 103 views
0

我有一些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格式的結果。

不知道這是否合理!前while循環,然後使用該變量

$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> 
+0

您需要向我們展示了實際的代碼。 –

+0

[PHP:「注意:未定義的變量」,「注意:未定義的索引」和「注意:未定義的偏移量」的可能重複](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable- notice-undefined-index-and-notice-undef) –

+0

不是@MagnusEriksson,它不是。 – Tom

回答

1

設置標誌變量來決定是否對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 
} 
?> 
+0

非常感謝你! – Tom

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