mn6vdv23g
mn6vdv23g

Reputation: 734

Get the last Id from database to a string/Int variable

I have to get the biggest id to a string or an int variable.

That is how I'm doing it:

$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
    $list = mysql_query($sql) or die (mysql_error());
    $lst = mysql_fetch_array($list);
    $resId= $lst[0];

ResId is that variable.

Is this going to work?

Is there a better way to do it?

There is no AUTO_INCREACMENT!

Upvotes: 0

Views: 1053

Answers (2)

u_mulder
u_mulder

Reputation: 54831

If last id is the biggest id (as I see from your query), then you can also use:

$q = 'select max(id) as max_id from `b_iblock_element`';
$q_res = mysql_query($q);
$row = mysql_fetch_assoc($q_res);
$max_id = intval($row['max_id']);

And don't forget that mysql_* functions are deprecated and will be removed soon.

Upvotes: 0

lawls
lawls

Reputation: 1508

If you don't auto increment or in any other way organize your id:s, there is no way to know which was the last one. (Unless you get the last inserted id when you're doing an insert query.)

Your query returns the greatest id, but if you haven't structured your code/table so that the greatest id is the last - then it won't return the last id obviously (oh well, it could).

As for your question if it will work. Why don't you simply try it out? You're much more likely to learn from trying your self than asking people for answers all the time.

Upvotes: 1

Related Questions