Wednesday, May 16, 2012

Perl and MySQL - Return a field from last row of a table using DBI possibly with last_insert_id?

I am trying to return a members firstname field from the table users from the last row of users.



 my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
my $LastID = $dbh->last_insert_id(`firstname`); ##but I want from table users
print qq~$LastID~;


This error is returned from above:



DBI last_insert_id: invalid number of arguments: got handle + 0, expected handle + between 4 and 5
Usage: $h->last_insert_id($catalog, $schema, $table_name, $field_name [, \%attr ])


So, what would be the "best" way (best being best for server, fastest, least memory, load, least amount of overhead.. whatever) to get the field firstname from the last row in the table users?



Realize my example above is not to be taken seriously as I have no idea how to do this without just doing something like my crude, but functional:
(p.s. UserID is NOT assigned by auto increment but, is in numeric order and a new user gets a higher UserID. Just the way this was when I tackled the pre existing problem.)



my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
my $dsn = $dbh->prepare(qq{SELECT `firstname` FROM `users` ORDER BY ABS(UserID) DESC LIMIT ?,?});
$dsn->execute('1','1') or die "$DBI::errstr";
while(@nrow = $dsn->fetchrow_array()) {
$newestid = $nrow[0];
}


I assumed since I was using DBI that may provide the best solution but, I am inexperienced obviously and need some advice and guidance to learn the proper way to do this. Thanks for any assistance.





No comments:

Post a Comment