Ghanshyamji Gupta
Ghanshyamji Gupta

Reputation: 429

How to show records in php from database in specific order

I am making a program in php to select records from database in alphabetical order by adding, "order by 'column name'" in my query string

for example we have entries

A B M L H V V F now after showing records in alphabetical order it will fetch records in following order

A B F H L M V V

now if a my user want to see records of m then he should get records in following manner

M A B F H L V V

means searched record at top and then in alphabetical order.

So how can I get records in this manner by one query

$result=mysqli_query($con,"SELECT * from orders order by 'name'");

Upvotes: 3

Views: 944

Answers (3)

SpacePhoenix
SpacePhoenix

Reputation: 605

Use two queries, the first grabbing all records for the the required letter, using the query in the question as a starting point (assuming required letter is M):

SELECT * FROM orders WHERE name LIKE '%m' ORDER BY 'name'

then for the second query:

SELECT * FROM orders WHERE name NOT LIKE '%m' ORDER BY 'name'

Then have PHP append the result set from the second query to the result set of the first. The field that is used in the ORDER BY clause will need to match in both queries. I don't think it's possible to do if you want both parts sorted in order in one query

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 6661

Use order by name='M' desc

SELECT * from orders order by name='M' desc,name ASC

Upvotes: 1

Suyog
Suyog

Reputation: 2482

You can try this

select * 
from orders
order by name = 'M' desc, name asc

Or

select * 
from orders
order by case when name = 'M' then -1 else name end

Source: mysql SQL: specific item to be first and then to sort the rest of the items

Upvotes: 1

Related Questions