Josh Josh - 1 month ago 5
MySQL Question

How to get_results from the database and display sorted in a table

I am trying to display information from a table I created in my Wordpress plugin (code below) and I can display in the table without any issues but I am having trouble figuring out how to display in some sort of sorted order, I.E. sorted by row ID.

<?php

echo "<table class='widefat'>"; // start a table in HTML
echo "<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Serial Number</th>
<th>UserID</th>
<th>Owner</th>
<th>Name</th>
<th>AreaCode</th>
<th>Number</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th>Select</th>
<th>Id</th>
<th>Serial Number</th>
<th>UserID</th>
<th>Owner</th>
<th>Name</th>
<th>Area Code</th>
<th>Number</th>
<th></th>
</tr>
</tfoot>
<tbody>";


$result = $wpdb ->get_results( "SELECT * FROM wp_new_table ");
foreach($result as $row){
echo "<tr><td><input name='ID_selected' type='radio' value='" . $row->id. "' /></td><td>" . $row->id. "</td><td>" . $row->sn. "</td><td>" . $row->userid. " </td><td>" . get_user_display_name($row->userid) ."</td><td>" . $row->name. "</td><td>" . $row->areacode. "</td><td>" . $row->phone. "</td><td>

<a href='" . $_SERVER['REQUEST_URI'] . "&dbviewedit=" . $row->id . "'>View/Edit</a></td></tr>";


}

echo "</tbody></table>";
?>

Answer

you have to adjust the SQL request, since the result is already not ordered

SELECT columnname FROM tablename ORDER BY columnname ASC|DESC

I hope this is what you're looking for

Comments