Doe Doe - 3 months ago 9
MySQL Question

Hide all the html table where there is no result from mysql database

I'm trying to make a dropdown menu where the user chooses a letter and then outputs all the names which start with this letter in a table I created.
The names are selected from a database. Now I want this table to be hidden when the user hasn't chosen a letter yet or when there are no results from the database. So I want the table to show up only when there is a result from the database. Here is my code:



<html>

<head>
<title>Title</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 5px;
}
th {
text-align: left;
}
</style>

</head>

<body>
<?php $con=mysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova'); if (!$con) { die( 'Could not connect: ' . mysqli_error($con)); } ?>
<form method="post">
<select name="users">
<option value="">Scegliete una lettera:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<input type="submit" name="submit" value="Go" />
</form>
<br>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
</div>
<table id='results'>
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>
<?php $q=$ _POST[ "users"]; //$sql="SELECT * FROM presta_prova WHERE marca LIKE 'B%' " ; $sql="SELECT * FROM presta_prova WHERE marca LIKE '" . $q . "%' "; $result=mysqli_query($con,$sql); while($row=mysqli_fetch_array($result)) { echo "<tr>"; echo
"<td>" . $row[ "marca"] . "</td>"; echo "<td>" . $row[ "descrizione"] . "</td>"; echo "</tr>"; } echo "</table>"; ?>
</table>
</body>
<?php mysqli_close($con); ?>

</html>





I try to insert a hidden attribute but it doesn't solve the problem. Can someone tell me how to make it hidden for the cases above? Thanks!

Answer

Here is the logic

<?php
$con=mysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova'); if (!$con) { die( 'Could not connect: ' . mysqli_error($con)); } 
$sql= mysqli_query($con, "SELECT * FROM presta_prova WHERE marca LIKE 'B%'") ;
$row = mysqli_fetch_assoc($sql);
$totalRows_results = mysqli_num_rows($sql);     
?>


<?php if($totalRows_results > 0) { ?>

Anything inside here will be visible if the query returns any result
//e.g you may echo out your results here <?php echo $row['column']; ?>


    you can also do your while loop inside here
    <?php do { ?>
    //your repeating region
       <?php echo $row['column']; ?>  //i.e.  <?php echo $row['marca']; ?>
    <?php } while ($row = mysqli_fetch_assoc($sql)); ?>  

<?php } ?>



<?php if($totalRows_results == 0) { ?>

Anything inside here will be visible if the query does not return any result
//e.g you may display an error message here like. sorry no result found

<?php } ?>