Reputation: 1
I have some PHP code that sets variables from a database. I'll explain, please let me know if it does not make sense.
So, I have a query to select *
from the table if class = '$class'
. That all works I got it working.
I then set the variables like this $id = $row["id"];
and that all works, in my HTML code I have <p><?php echo $id?></p>
and if their class = $class
it will display it, however, if it does not meet those requirements the variables are not set, so I get the error Notice: Undefined variable: id in C:\wamp64\www\studentplanner\account\homework.php on line 73
.
What I want to do is only output the results in HTML if the requirement was met.
No idea if that makes sense or not!
$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>
Upvotes: 0
Views: 35
Reputation: 1301
$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 } } ?>
Upvotes: 0
Reputation: 16436
set flag variable before while loop then use that variable to decide whether to print data in html or not
$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
}
?>
Upvotes: 1