Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Single Row Query with MySQL and PHP

Tags:

php

mysql

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/>';
}
like image 790
Supernovah Avatar asked Nov 26 '25 10:11

Supernovah


1 Answers

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.

like image 190
Soviut Avatar answered Nov 28 '25 01:11

Soviut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!