Forum Moderators: open

Message Too Old, No Replies

MySQL

total number of rows, select last x rows

         

dgsk387

5:52 am on Dec 2, 2007 (gmt 0)

10+ Year Member



Is there a way to determine how many rows of data there are in a SQL DB WITHOUT doing this:

$sql = "SELECT id FROM photos";
$result = mysql_query($sql) OR die("Couldn't select Data.");
$num = mysql_numrows($result);

With that code it seems like a waste to have to select a bunch "id"s just to find out how many rows there are. What if there were 1,000,000 rows? Isn't the code a bit resource intensive?

I want to select a random id (row of data) from the database but first I need to know the total number of rows right?
For example, I need to know that there are 200 rows (ids) so that I limit my random number to 200 or below correct?

So I'm curious about if there are any other ways to know how many rows there are.

===
Also, does anyone know how to select the last 5 rows of a database without knowing how many total rows there are? Like if I wanted to display the last 5 rows of data that were added.

Many thanks.

ZydoSEO

6:00 am on Dec 2, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



SELECT COUNT(*) FROM PHOTOS

should tell you how many rows are in that table...

phranque

9:29 am on Dec 2, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you might want to do something like:
SELECT COUNT(*) AS photo_count FROM photos
so you have a nice useful key.

regarding your last question, if id is an autoincrement column:
SELECT * FROM photos ORDER BY id DESC LIMIT 5

dgsk387

6:38 pm on Dec 3, 2007 (gmt 0)

10+ Year Member



awesome, thanks guys!

I can always count on receiving great help here!

dgsk387

6:48 pm on Dec 3, 2007 (gmt 0)

10+ Year Member



awesome, thanks guys!

I can always count on receiving great help here!