Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

highest number in a query

Status
Not open for further replies.

jefargrafx

Instructor
May 24, 2001
273
US
I'm try to fix a problem in some code that I inherited.

The script use $count to count the number of items in a query. And then add 1 to the count to create new entry.

cool unless you delete say number 3 from 1-5 and then add another

the count returns 4 and over writers 5 as 4.

I need to know the highest number in the query and drawing a blank on how to do this?

any ideas

thanks

jef
 
Insufficient data for a meaninful answer.

What do you mean by "query"?

Is all the data from the "query" stored in PHP variables, or is the script doing something like looping through a mysql_fetch_assoc() operation?

What is the nature of the delete operation?



Want the best answers? Ask the best questions! TANSTAAFL!
 
i don't fully follow the issue.

if you want to add an item to a numeric array you can just use an implicit assignment
Code:
$array[] = "new item";
this will automatically add an item to the end of the array with the key as the (largest previous key + 1)

if you MUST know the numeric index of the last item in the array you could use this
Code:
function getMaxKey($array){
 end($array);
 return key($array);
}
there may well be a neater way of doing it.
 
got it working,

I just had to do another query and tehn check if it return anything or not, if so, up the id by one, if not, continue.

thanks for the input your getMaxKey function set me on the right track.

sometimes that all it takes

jef
 
if you are using a database and your key is not an autoincrementer, then i'd consider using a random key instead of an incremented integer (the following will give you good pseudo randomisation)
Code:
$key = md5(uniqid("", true));

 
if you're obtaining your data from a database, then you could use the max() on the primary key field. For example:

select max(the_id) from the_table

this query will return 1 row, which contains the greatest value for the "the_id" field.

Hope this helps.

sites I like: .. let's me find new movies to watch :)
 
and would it not be neat to be able to run a query like
Code:
insert into the_table
set 
id = (select max(id) from the_table) + 1,
anotherfield = "some value"
but unfortuntely this cannot be done with the current version of mysql.

although ... just a thought ... might it be possible to address a view of the_table rather than the_table itself?


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top