Dynamic combobox

Let’s suppose we want to filter using data from a combo box (“Option” item). To use real-time date, based on the content of the database, we can use the code below.

Filling combobox

<?php
$sql = "SELECT DISTINCT adresa FROM info ORDER BY adresa";
$result = mysqli_query($con, $sql);
?>
<table class="tabel_form">
<tr>
<td>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="adresa" id="adresa">
<option disabled selected value> -- Alege o ţară -- </option>
<?php
while($adr = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<option value=" .$adr['adresa'] . ">" . $adr['adresa'] . "</option>";
}
?>
</select>
</td>
<td>
<input type='submit' value = 'Filtrare'>
</form>
</td>
</tr>
</table>
</form>

Display filtered content

<?php
// Variabila pentru evitare injectii
$adresa = mysqli_real_escape_string($con, $_POST['adresa']);
$sql_query = "SELECT * FROM info
WHERE adresa='$adresa'
ORDER BY adresa";
?>
<table id="data_table" class="catalog">
<thead>
<tr>
<th>Id</th>
<th>Nume</th>
<th>Tara</th>
</tr>
</thead>
<tbody>
<?php
echo "<div class=\"obs\" style=\"\">Afişaţi clienţii pentru <strong>".$adresa."</strong>.</div>";
$rez_toate = mysqli_query($con, $sql_query);// or die("database error:". mysqli_error($con));
while( $tara = mysqli_fetch_assoc($rez_toate) ) {
?>
<tr id="<?php echo $tara ['id']; ?>">
<td><?php echo $tara ['id']; ?></td>
<td><?php echo $tara ['nume']; ?></td>
<td><?php echo $tara ['adresa']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

Author: Ovidiu.S

I am quite passionate about this professional area as if I know something - no matter how little - I want to share it with others.

Leave a Reply