Page 1 of 1

mysql_insert_id()

Posted: Wed Aug 24, 2005 9:43 am
by ale2121
hi, could someone explain mysql_insert_id() to me?

I'm uploading files to an upload folder, but they just keep getting named the same thing, and writing over each other. here's a bit of my code:

$extension = explode('.',$_FILES['upload']['name']);
$uid = mysql_insert_id();
$filename = $uid.'.'. $extension[1];

couldn't I just use the original name ($_FILES['upload']['name']), i hear this is somehow a security issue.

Posted: Wed Aug 24, 2005 9:45 am
by feyd
mysql_insert_id() returns the last created Primary Key mysql added for an insert command within the last connection space.

I think you want something like uniqid() instead.

Posted: Wed Aug 24, 2005 9:47 am
by Grim...
mysql_insert_id() simply gives you the index id of the last thing you inserted into a database.

Try something like:

Code: Select all

$filename = rand(1, 10000000).'.$extension[1];
while (file_exists($filename))
{
    $filename = rand(1, 10000000).'.'.$extension[1];
}

Posted: Wed Aug 24, 2005 9:47 am
by Grim...
Or what Feyd said ;)

Posted: Wed Aug 24, 2005 10:36 am
by ale2121
ok so in fact yes both of you do rock, you get an A+ in response time, 2 cookies and 4 gold stars (for what it's worth).
however, i tried both suggestions and feyd's returned a fatal error,
and Grim's returned a parse error. I feel like I should have been capable of figuring out the parse error, but I couldn't. so, what i tried to do was go back to my original code. i added a new column in my table smallint(4), auto_increment, and assigned it as the primary key, and now I'm getting an error that tells me there's a duplicate (0) key. I'm thinking this is because it's somehow not incrementing the key for each uploaded file.

Posted: Wed Aug 24, 2005 10:38 am
by ale2121
oh, and did i mention that i can't upload anything at all now?

Posted: Wed Aug 24, 2005 10:39 am
by Grim...
Changed mine ;)

Posted: Wed Aug 24, 2005 11:58 am
by ale2121
works ! here's the code: ( in case someone else has the same problem)

Code: Select all

$extension = explode('.',$_FILES['upload']['name']);
		$filename = rand(1,1000000).'.'. $extension[1];
			while (file_exists($filename)) {
				$filename = rand(1,1000000).'.'.$extension[1];
			}