I'm quite new at PHP and have created a simple table that gets the data from a mysql database and displays it. However I want that, when the 'region' field has no records, to get a message 'No records' instead of the table. On the other hand, if the 'region' field has data, then the table should appear normally.
So, in the example below, if there are no records for the region'Alsace', no table should appear...
It seems quite simple in principle, but I cannot seem to find a way of doing this... .
Here is my code:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = "tournois";
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Could not connect : " . mysql_error());
mysql_select_db($db, $conn)
or die("Could not select database");
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
$query = "SELECT date, tournoi, lieu, region, prix,ritme, link FROM tournois_france WHERE region = 'Alsace'";
$result = mysql_query($query);
if ($result){?>
<table class='table table-hover'>
<tr class=info>
<th>Date</th>
<th>Tournois</th>
<th>Lieu</th>
<th>Region</th>
<th>Prix</th>
<th>Ritme</th>
</tr>
<?php while($row = mysql_fetch_array($result)) {?>
<tr>
<td><?php echo $row->Date;?></td>
<td><?php echo $row->Tournoi;?></td>
<td><?php echo $row->Lieu;?></td>
<td><?php echo $row->Region;?></td>
<td><?php echo $row->Prix;?></td>
<td><?php echo $row->Ritme;?></td>
</tr>
<?php }?>
</table>
<?php } ?>
Try the below,
Use mysql_num_rows
this will check the return rows count
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = "tournois";
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Could not connect : " . mysql_error());
mysql_select_db($db, $conn)
or die("Could not select database");
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
$query = "SELECT date, tournoi, lieu, region, prix,ritme, link FROM tournois_france WHERE region = 'Alsace'";
$result = mysql_query($query);
if (mysql_num_rows($result) !=0){?>
<table class='table table-hover'>
<tr class=info>
<th>Date</th>
<th>Tournois</th>
<th>Lieu</th>
<th>Region</th>
<th>Prix</th>
<th>Ritme</th>
</tr>
<?php while($row = mysql_fetch_array($result)) {?>
<tr>
<td><?php echo $row->Date;?></td>
<td><?php echo $row->Tournoi;?></td>
<td><?php echo $row->Lieu;?></td>
<td><?php echo $row->Region;?></td>
<td><?php echo $row->Prix;?></td>
<td><?php echo $row->Ritme;?></td>
</tr>
<?php }?>
</table>
<?php }else{ ?>
<h4>No data found </h4>
<?php } ?>
Use MySQL num rows. Generate the table if row count is greater than zero