How does lastInsertId() work for tables without auto-incremented fields? - php

How does lastInsertId() work for tables that do not have an auto-incremented field? What about tables where the primary key is made up of 2 fields?
(I'm working with MySQL)

In both cases above it will return 0.
When using an auto_increment column, it will return the last INSERT ID even if it was specified (i.e. the auto increment was not used).
That is to say you should only use lastInsertId when using auto increment. It doesn't really make sense to use it otherwise since you would have to know the keys ahead of time anyway..

I don't think it does as it is a function specifically designed to be used to retrieve the value of an AUTO_INCREMENT field.
http://php.net/manual/en/function.mysql-insert-id.php
mysql_insert_id
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
This type of thing is easy enough to test - have you tried it to see what happens?

Related

Can mysqli_insert_id be broken by multiple scripts hitting a database at once? [duplicate]

I want to write a function that returns the value of a column (in this case, an auto-incrementing primary key) for a row that it inserts.
Essentially, I want to insert some new data, have a new primary key generated, then get that key. I could simply look for the highest primary key in the table, but it is possible that someone else could be running the function as well, and I could return the wrong key, right?
What's the simplest way to negotiate this problem?
As pointed in the comments, from MySQL documentation:
mysql> SELECT LAST_INSERT_ID();
-> 195
This LAST_INSERT_ID() function is not subject to a race condition like SELECT MAX(id) might be, because it's maintained within MySQL specific to your connection. It returns the ID generated for your last insert, not anybody's last insert.

Will msql_insert_id() give me an incorrect result if another autoIncrement happens before I call it?

I'm trying to add a row to a table, and then immediately get its unique ID, which is simply an autoincremented column.
Googling tells me PHP can do this through the mysql_insert_id() method, which
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
Is the "previous query" limited in scope to this specific connection, or is it possible that if somehow another row is inserted before I call it, it will return the wrong ID?
Are there any better suggestions on how to get or set a unique ID for a row? I'd make the unique ID on the client-side, but there are multiple clients, so that's not really possible.
Thanks.
Yes, it's limited to connection, so it will return a reliable value.
Try to use mysqli-functions or PDO, MySQL will be deceprated.

PHP mysql_insert_id() for MySQL UUID() primary keys?

Is there some equivalent to PHP mysql_insert_id to fetch the last inserted UUID() primary key? (I always get 0. It works for auto_inc integers though)
No, last_insert_id() only retrieves that last generated auto_increment fields. You'll have to do a select uuid() first, then do an insert using that uuid.
However, note that uuids can't be guaranteed to be unique - they're simply very unlikely to collide. If you do require uniqueness, then go with an auto_increment - they'll never be re-used within any single table.
I found this quite short and simple solution:
set #id=UUID();
insert into <table>(<col1>,<col2>) values (#id,'another value');
select #id;

How do I know when a field/row in mysql updated successfully?

Right now, I have my database setup so that I insert a new row. But if the row I'm trying to insert is a duplicate (based off of my primary key id), then I increment the count field by 1.
Right now I want to know when I was able to create a new row instead of having it increment count. How would I do this in an efficient/proper manner?
The current method I'm thinking of doing this, is by querying the id first and checking if it exists. But I feel like there's a faster/better way. I've also read about triggers but I've heard that they're bad/risky to use.
Use INSERT ... ON DUPLICATE KEY UPDATE...
Then query for affected_rows (as #Tarek Fadel suggested). MySQL will return 1 if the row was inserted, or 2 if existing row were updated.
Use your database AUTO INCREMENT option for your primary ID field. Only propper solution.
Here you have mysql reference, but that exist in just every database engine:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
How about an auto_increment on the id column?
Otherwise you might use SELECT MAX(id) FROM TABLE to retreive the highest id and add one to it, but that isn't thread-safe since another user might execute the same insert at the same time. Auto_increment fixes that for you.
PHP's mysql_affected_rows()

What's the standard way to determine the number for a primary key?

I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused.
A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.
In MySQL that's the standard solution.
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
Unless you have an overriding reason to generate your own PK then using the autoincrement would be good enough. That way the database manages the keys. When you are inserting a row you have to leave out the primary key column.
Say you have a table table = (a, b, c) where a is the primary key then the insert statement would be
insert into table (b, c) values ('bbb', 'ccc')
and the primary key will be auto inserted by the databse.
AUTOINCREMENT is what you want. As long as you don't change the table's settings, AUTOINCREMENT will continue to grow.
AUTOINCREMENT is the standard way to automatically create a unique key. It will start at 1 (or 0, I can't remember and it doesn't matter) then increment with each new record added to the table. If a record is deleted, its key will not be reused.
Auto increment primary keys are relatively standard depending on which DBA you're talking to which week.
I believe the basic identity integer will hit about 2 billion rows(is this right for mySQL?) before running out of room so you don't have to worry about hitting the cap.
AUTO_INCREMENT is the common choice, it sets a number starting from 1 to every new row you insert. All the work of figuring out which number to use is done by the db, you just ask it back after inserting if you need to ( in php you get it by callin mysql_last_insertid I think )
For something simple auto increment is best. For something more complicated that will ultimately have a lot of entries I generate a GUID and insert that as the key.

Categories