How can PHP be used to dynamically sort a table via MySQL without using a table sorter with JavaScript?
To dynamically sort a table via MySQL without using a table sorter with JavaScript, you can achieve this by using PHP to handle the sorting logic. You can pass the sorting criteria through URL parameters and then dynamically construct the SQL query based on those parameters to fetch the sorted data from the database.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the sorting criteria from URL parameters
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'default';
// Construct the SQL query based on the sorting criteria
$sql = "SELECT * FROM table_name ORDER BY $sort";
$result = $conn->query($sql);
// Output the sorted table data
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['column1'] . "</td><td>" . $row['column2'] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- How can PHP developers ensure that their code is readable and searchable by avoiding image attachments in forum posts?
- Are there any potential pitfalls to be aware of when converting CSV data to an Excel file in PHP?
- How can PHP developers ensure compatibility with older versions of PHP when using functions like http_build_query()?