473,394 Members | 1,709 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Fetching the last row in a table with a single varchar field.

hi can anybody tell, how can i fetch last record from table.
In that table only one varchar type column is there like name
Apr 24 '07 #1
13 12852
code green
1,726 Expert 1GB
What do you mean by `lasr record`?
Apr 24 '07 #2
Hi,
Last record means newly inserted record.
and we should get that record only not more than that .And that record should get by using select statement not the insert statement.
Apr 25 '07 #3
code green
1,726 Expert 1GB
Why not have another field of data type DATETIME?
Apr 25 '07 #4
michaelb
534 Expert 512MB
Why not have another field of data type DATETIME?
Because if DATETIME granularity is one second you still won't be able to identify the last record any time when more than one record inserted within the same second.

An auto_increment id seems like a better choice.
Apr 26 '07 #5
Yes. This is ok. can not we get last inserted record with out timestamp and auto increment.

Thank u for ur reply
Apr 26 '07 #6
code green
1,726 Expert 1GB
Sounds like you have met this before michaelb. In answer to the problem I don't see how this can be done. I have had the same problem with files rather than records. I got round it by adding a numeric suffix to the file. Could you tag a number onto the record entry then use string functions to strip out the numbers and compare them?
Apr 26 '07 #7
balabaster
797 Expert 512MB
What type of database are you using?

If you are using SQL Server you can use the Scope_Identity() value which records the identity of the primary key of the last inserted record within your scope. If someone inserts a record in a different scope, you still get your record back. Oracle also has a similar ability.

If you're using MS Access it becomes a little more complex as it doesn't support such a feature. You need to use a different means of doing this. If someone else inserts a record inside your time window then you run the risk of getting their record instead of yours. In order to alleviate that issue, you would need to lock the table on insert and not unlock it until you've retrieved the key to prevent someone else screwing up your app. This method has its own drawbacks that you need to consider.

For generally getting the last record, you just do "Select * From <Table_Name> Where <Primary_Key_Field> = (Select Max(<Primary_Key_Field_Name>) From <Table_Name>)". However, this one won't take into account records inserted from other scopes (i.e. by other users) in the period between your insert and your select.
Apr 26 '07 #8
balabaster
797 Expert 512MB
What type of database are you using?

If you are using SQL Server you can use the Scope_Identity() value which records the identity of the primary key of the last inserted record within your scope. If someone inserts a record in a different scope, you still get your record back. Oracle also has a similar ability.

If you're using MS Access it becomes a little more complex as it doesn't support such a feature. You need to use a different means of doing this. If someone else inserts a record inside your time window then you run the risk of getting their record instead of yours. In order to alleviate that issue, you would need to lock the table on insert and not unlock it until you've retrieved the key to prevent someone else screwing up your app. This method has its own drawbacks that you need to consider.

For generally getting the last record, you just do "Select * From <Table_Name> Where <Primary_Key_Field> = (Select Max(<Primary_Key_Field_Name>) From <Table_Name>)". However, this one won't take into account records inserted from other scopes (i.e. by other users) in the period between your insert and your select.
Sorry, didn't realise this was MySQL - I would use the same method using a table lock as I would in MS Access. Lock the table for your own use, complete the insert and corresponding select and then unlock the table.
Apr 26 '07 #9
hi can anybody tell, how can i fetch last record from table.
In that table only one varchar type column is there like name
Using MySQL?? It's easy: LAST_INSERT_ID( ).

i.e.
1st Query:
INSERT INTO whatevertable (field1, field2) VALUES ('oh my', 'oh gee');

2nd Query:
UPDATE whatevertable set field1='cool stuff' WHERE id=LAST_INSERT_ID( )
May 14 '07 #10
code green
1,726 Expert 1GB
LAST_INSERT_ID() only works on AUTO_INCREMENT field. For reasons that defy belief prashanth023 has only one field in this table and it is a VARCHAR. At least that's how I understand the problem.
May 14 '07 #11
Atli
5,058 Expert 4TB
Why create a table with only one text field?
It is a basic rule of relational databases, as well as just common sence, to have a unique primary key for each table.
May 15 '07 #12
waho.. not sure if its too late..
you may do this;
Expand|Select|Wrap|Line Numbers
  1. $id = mysql_query("SELECT * FROM tablename ORDER BY id DESC");
  2. $id = mysql_fetch_array($id);
  3. $id = $id[id];
  4.  
$id will now store the last inserted if without auto_increament enabled
Feb 17 '09 #13
Atli
5,058 Expert 4TB
@jakekoh
Hi.

A few notes on your code.
  • Most importantly, this code fetches the entire table, just to get the highest ID listed. This is extremely inefficient, seeing as only a single integer out of all that data is actually needed.
    Your site is extremely likely to take a performance hit if you were to use this method.
    Use the LIMIT clause to reduce the number of rows returned.
    (See 12.2.8. SELECT Syntax in the manual)
  • You should always try to avoid using the wild-card character (*) when specifying which columns to select, and rather specify which columns you need. That way MySQL does not have to return a bunch of data that you will never use. Also, by specifying the columns in the query, any errors in the column names will be treated as SQL errors, rather than PHP undefined index errors, which is arguably easier to debug.
  • When you fetch associative array elements (elements named using a string), you should use a string. And all strings should be quoted.
    If you do not quote a string, PHP will assume it is a constant. If that constant does not exists, PHP may assume you meant to use a string and convert it for you, but you have no guarantee that this behavior will work consistently across different PHP versions, which could cause problems later on.
  • Reusing the same variable ($id) over and over again, like you do, is a very bad idea from a design perspective.
    It makes the code very hard to read, and makes it very easy for you, or whoever may need to read your code later on, to confuse variables and make a mistake.
    You should always give your variables distinctive names, so their purpose and content can be easily identified.
So, with that in mind, I would try doing something more like:
Expand|Select|Wrap|Line Numbers
  1. $query = "SELECT `id` FROM `tablename` ORDER BY `id` DESC LIMIT 1";
  2. $result = mysql_query($query) or die(mysql_error());
  3. $row = mysql_fetch_array($result);
  4. $id = $row['id'];
Note that I added a die() call in case the SQL query fails. This shows the error, if any, in case the SQL query fails.
Feb 17 '09 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Steve | last post by:
I'm trying to do a multi table query that displays all the info I need in one array, and I'm having problems figuring out how to do it. The two tables are product and vendor. A vendor can be a...
1
by: Omavlana | last post by:
Hi, How can I create a temporary table say "Tblabc" with column fields ShmCoy char(2) ShmAcno char(10) ShmName1 varchar(60) ShmName2 varchar(60) and fill the table from the data extracted...
7
by: Rick Caborn | last post by:
Does anyone know of a way to execute sql code from a dynamically built text field? Before beginning, let me state that I know this db architecture is built solely for frustration and I hope to...
9
by: mfyahya | last post by:
Hi, I'm new to databases :) I need help speeding up select queries on my data which are currently taking 4-5 seconds. I set up a single large table of coordinates data with an index on the fields...
9
by: expect | last post by:
Hello, Trying to get this MySql create table command to work, no luck. create sequence serial; CREATE TABLE outbound ( source char(100) default '', destination char(100) default '', sport...
22
by: Sandman | last post by:
So, I have this content management system I've developed myself. The system has a solid community part where members can register and then participate in forums, write weblogs and a ton of other...
0
by: ceejee | last post by:
im trying to create a table as shown below. i tried to set a default value for a certain field but an error is occuring. can you give me insight where is the hole in my coding? im using asp and the...
0
debasisdas
by: debasisdas | last post by:
We can fetch from a cursor into one or more collections: DECLARE TYPE NameList IS TABLE OF employees.last_name%TYPE; TYPE SalList IS TABLE OF employees.salary%TYPE; CURSOR c1 IS SELECT...
13
by: ramprakashjava | last post by:
hi, i hav "java.lang.NullPointerException" error while Deleting table records using checkbox in jsp here i enclosed files help quickly plzzz.. ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.