Last id inserted help

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
lparnau
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 3:31 pm

Last id inserted help

Post by lparnau »

:oops: A little help please. I am not new to programing, but brandnew to PHP & mySql.

I need to query a data base for the largest id #. This needs to be done each time the script is run. This # then needs to be placed into a var. so it can be used as the upper range for rand(0, $Lastid).

I have tried


<?php

$db = mysql_connect("localhost", "axxxxxli", "xxxxxxxxxx");

mysql_select_db("dxxxxxxxst_com3",$db);
$result = mysql_query("SELECT * FROM random_db",$db);

-----------------I tried-----------------------

$Lastid = mysql_insert_id(); ......... // All I get from this is the #0

-----------------I also tried-----------------------

$Lastid = mysql_insert_id($result); ......... // This did not work at all No # returned.

-----------------I also tried-----------------------

$Query = "SELECT LAST_INSERT_ID()";
$Result = mysql_query($Query, $db);
$row = mysql_fetch_array($Result);
$Lastid = $row[0]; ................... // This also returnes only #0



if($ID) {

$Lastnum = $ID;

}else{

$Lastnum = rand(0, $Lastid);
}

printf("%s\n\n", $Lastnum);

printf("%s\n\n", $Lastid);

?>

Is there a way to do this with out having to capture the number when it is iinserted then storing it in a var. in my db table :?:
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

"SELECT MAX(column) AS column FROM table";
lparnau
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 3:31 pm

Post by lparnau »

I do not understand why this is a cross post, I am sorry. Please tell me where should I ask questions about using databases. I was only asking about the function for finding the number. I only put in the little snip of code to show my uses of the function. If this is not allow as I said I am really sorry.

Leonard
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

lparnau wrote:I do not understand why this is a cross post, I am sorry.
Don't mind, it's part of McGruff's signature. It is not directed to you personally.

Cheers,
Scorphus.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Rgr all OK.
Stoneguard
Forum Contributor
Posts: 101
Joined: Wed Aug 13, 2003 9:02 pm
Location: USA

Post by Stoneguard »

Here are the changes I would make to your code:

Code: Select all

<?php
$db = mysql_connect("localhost", "axxxxxli", "xxxxxxxxxx"); 

mysql_select_db("dxxxxxxxst_com3",$db); 
$sql = "select max(<fldname>) as MyId from random_db"

$result = mysql_query($sql, $db);

$row = mysql_fetch_array($result);

$ID = $row[$col];

...
?>
Post Reply