tags:

views:

39

answers:

3

How to fetch the first two rows from Mysql DB using Mysql PHP function? Is there any function which can give me first 2 or 3 rows from the select query we fired?

+2  A: 

Use LIMIT. From the manual, to retrieve 3 rows:

SELECT * FROM tbl LIMIT 3; 

Or to retrieve rows 6-15:

SELECT * FROM tbl LIMIT 5,10;

For this query (i.e. with no constraint) if you are not using an ORDER BY clause your results will be ordered as they appear in the database.

Andy
I think I am gone out of my mind...I dont believe this that I asked this question...Thanks Mate for the reply and alerting me that I am tired.....
OM The Eternity
lol no worries, happens to the best of us :)
Andy
Thanks Again for the condolence :)
OM The Eternity
If you are not using an ORDER BY clause your results will be ordered **ran-dom-ly**.
Col. Shrapnel
Orrite, I did that before asking this Blunder :)
OM The Eternity
@ the belligerent Colonel: do you have any **ref-er-en-ces**? I tend to find `LIMIT 3` gives me the first three rows that I see from `SELECT * FROM tbl`. If they were random why would one search for the most optimised manner in which to randomise results? http://jan.kneschke.de/projects/mysql/order-by-rand/
Andy
+1  A: 

You can use the limit clause in your query:

select * from your_table limit 3

This will select the first three rows.

And:

select * from your_table limit 5, 3

The later will select rows starting from 5 and return three rows.

Sarfraz
Thanks Sarfraz for the detailing
OM The Eternity
@OM The Eternity: You are welcome...
Sarfraz
A: 

You have 2 options:

  1. Fire a query to select all the rows and then select 2 or 3 rows as needed using PHP.
  2. Fire a query to select only the necessary number of rows using LIMIT clause.

The 2nd option is preferable.

codaddict
Thanks unicornaddict for the "Points to Remember Style" will keep in mind :)
OM The Eternity