Janel Sangalan
Janel Sangalan

Reputation: 41

PHP Hiding a button if data exist

I'm trying to Hide the button if "name" is empty no error show but the button is still showing I tried adding css to it but the button still show

 <table style="width:100%" border="1px">
<tr align="center">
  <th>Name</th>
  <th>Image</th>
  <th>PDF</th>
  <th>Grade</th>
  <th>Date</th>
</tr>
  
<?php

foreach ($records as $value) {
  $id = $row['id'];
  echo '<tr align="center">';
  echo "<td>" . $value['name'] . "</td>";

if ($value['name']  != ''){
echo "<td> <a  class='design' style='display:none;' href='".$value['img_name']."'>Download image</a></td>";
}else{
    echo "<td> <a  class='design' href='".$value['img_name']."'>Download image</a></td>";
}

  echo "<td><a class='cert' href='".$value['pdf_name']."' download>Download PDF</a></td>";
  echo "<td>". $value['score']."</td>";
  echo "<td>". $value['date']."</td>";
  echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

Upvotes: 2

Views: 1329

Answers (2)

FluxCoder
FluxCoder

Reputation: 1276

PHP has a function called empty, which can be used to determine if a variable is empty or not.

For your situation, I don't see why you would want PHP to output a button if it's simply going to be hidden by CSS afterwards.

In PHP, you could use the empty function like this:

<?php
$var4you = "";

if (!empty($var4you)) {
    //Display only when there is a value
}
?>

For you to you this within your code, you'd likely want to do this:

<?php
if (!empty($value['name'])) {
    echo "<td> <a  class='design' href='".$value['img_name']."'>Download image</a></td>";
}
?>

You can learn more about using the empty function in PHP in the docs: https://www.php.net/manual/en/function.empty.php

Upvotes: 0

Dennis
Dennis

Reputation: 538

Just add the class hide to the first if condition and add display: none to that class

HTML:

if ($value['name']  != ''){
    echo "<td> <a  class='design hide' href='".$value['img_name']."'>Download image</a></td>";
}else{
    echo "<td> <a  class='design' href='".$value['img_name']."'>Download image</a></td>";
}

CSS:

.hide { display: none; }

Upvotes: 1

Related Questions