I've written a bit of CSS and PHP to query a MySQL table. I also have a filter in the form of a drop down box which allows the user to choose a 'family', whether it be "capacitor", "resistor", or "ferrite bead" (I've included pictures below of what this looks like).
My question is this: how can I create a sorting system for the elements once they have been filtered by family? That is, if I wanted to query the table from MySQL corresponding to ASC values of "voltage" for example, how would I go about this? I need to retain the filter when the sorting method is selected. I have included my code so far below the images. Thanks for the help!
(Below: 1, full table is loaded : 2, only family entries that match "capacitor" are loaded)
CODE: (File name, index.php)
<html>
<form action="index.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
<head>
<meta charset = "UTF-8">
<title>test.php</title>
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
input: "text";
text-align: left;
padding: 8px;
}
th {
background-color: SkyBlue;
}
tr:nth-child(odd) {background-color: #f2f2f2;}
tr:hover {background-color: AliceBlue;}
</style>
</head>
<body>
<p>
<?php
$family = "";
if(isset($_POST['family'])) {
$family = $_POST['family'];
}
try {
$con= new PDO('mysql:host=localhost;dbname=mysql', "root", "kelly188");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(!empty($family)) {
$query = 'SELECT * FROM testv2 WHERE family = "'.$family.'"';
}
else {
$query = "SELECT * FROM testv2";
}
//first pass just gets the column names
print "<table>";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
}
// end foreach
print " </tr>";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} //end field loop
print " </tr>";
} //end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
</p>
</body>
</html>

