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
- What is the basic PHP code structure for sending an email through a form?
- In PHP development, what are the best practices for organizing classes and handling database interactions, such as using interfaces for database queries and implementing Dependency Injection for registration and login functionalities?
- How can one ensure that parameters passed in PHP scripts are not visible in the browser's URL field?