John Davidson

php - unable to sort alphabatically when calling data from db

0 comments
Message:


I am trying to sort alphabetically. I am calling data from database. In the table i am storing ID's of Make like Suzuki, Toyota. I have 1 table naming Make in which i am saving Makes like Toyota.
then i am adding into Models with respect to Make like Land Cruiser is a model and its Make is Toyota. i am inserting ID of the Make from Make's table. then on front end, i am converting the ID's back to Make's name. I want to show Makes name alphabetically.


Here what i do


<?php
$SelectMainCats = mysqli_query($con, "SELECT * FROM model");
$S_NO = 0;
while($row=mysqli_fetch_assoc($SelectMainCats)){
$S_NO++;
$getid = $row['id'];
//converting ids to names
$main_make_query = mysqli_query($con,"SELECT * FROM make WHERE id=".$row['make']);
$main_make = mysqli_fetch_assoc($main_make_query);
?>

Front end calling


<td><?php echo $main_make['maker_name'];?></td>


My Answer:
You can achieve sorting alphabetically by using the ORDER BY clause in your SQL query when fetching data from the database. Here's an example query that you can use:

php
$query = "SELECT * FROM Make ORDER BY MakeName ASC";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
echo $row['MakeName'] . "
";
}


In this query, we are selecting all rows from the Make table and ordering them by the MakeName column in ascending order (ASC) which will sort the Makes alphabetically. You can then loop through the results and display the Make names on the front end.

Make sure to replace `MakeName` with the actual column name in your Make table that stores the Make names. Also, replace `connection` with your database connection variable.

This should help you display the Makes alphabetically on the front end. Let me know if you need further assistance.

Rate this post

4 of 5 based on 8448 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us