Page 1 of 1

Last id inserted help

Posted: Mon Oct 06, 2003 12:26 pm
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 :?:

Posted: Mon Oct 06, 2003 12:54 pm
by McGruff
"SELECT MAX(column) AS column FROM table";

Posted: Mon Oct 06, 2003 1:23 pm
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

Posted: Mon Oct 06, 2003 6:32 pm
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.

Posted: Mon Oct 06, 2003 7:11 pm
by McGruff
Rgr all OK.

Posted: Mon Oct 06, 2003 7:58 pm
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];

...
?>