3

say I have this

$result =  mysql_query('SELECT views FROM post ORDER BY views ASC');

and I want to use the value at index 30 I assumed I would use

mysql_data_seek($result, 30);
$useableResult = mysql_fetch_row($result);
echo $useableResult . '<br/>';

But that is returning my whole table

What have I got wrong?

Edit: Woops, I actually have

mysql_data_seek($result, 30);
while($row = mysql_fetch_row($result)){
    echo $row['views'] . '<br/>';
}

3 Answers 3

5

Simply use an SQL WHERE clause.

$result = mysql_query('SELECT views FROM post WHERE ID=30')

If you don't want to go by ID but instead want the 30th item that would be returned you can use a LIMIT min, max:

$result = mysql_query('SELECT views FROM post LIMIT 30, 1')

In both cases your ORDER BY commands become unnecessary.

Here is a good usage example of the LIMIT command for doing paging on large record sets.

Sign up to request clarification or add additional context in comments.

2 Comments

Cheers, I actually had a mistake in my own code and this didn't identify it but it usefull nonetheless. :)
The sample here is wrong: SELECT * FROM your_table LIMIT 5, 5 This will show records 6, 7, 8, 9, and 10 Check Ciaran McNulty's answer
2

Your first example would actually do what you want, but be very expensive. The second is selecting the entire table, moving to the 30th row of the result, and then looping through all the results from then onwards.

You should instead do the following, which will only return one row and be a lot faster:

$result =  mysql_query('SELECT views FROM post ORDER BY views ASC LIMIT 30,1');

Note that Soviut's explanation of LIMIT is not quite correct - it's (offset, number of rows) rather than (min, max).

1 Comment

Thanks, I fixed my example to keep the selected answer as accurate as possible.
0

Are you sure there are 30 elements in $result? You might want to check to see if 30 > mysql_num_rows().

1 Comment

My sample DB has 50000 elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.