I found the mysql_insert_id function to retrieve the last auto generated ID.
Should I be using mysql_insert_id +1 to add a new ID or is there a call for adding a new unique ID?
Using NULL for id:
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
OR not specifying id at all:
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
Either way works just fine, more of a preference but personally I chose the second as its less typing.
If your id field is set to auto increment, you don't have to add an ID at all. It will be incremented and added automatically.
AUTO_INCREMENT in MySQL does exactly what it sounds like. When you insert a new record it will automatically generate a new ID for you. You do not need a separate call.
Insert a new record and set the auto-increment column to NULL, or just omit it entirely (which is implicitly setting it to NULL - it has the same result). The column will be set to the next auto-increment value instead of NULL.
When you delete a row and you insert again an another row, the new inserted id is not the same as what you delete before you insert again. example you have 3 row and the id value is 1, 2, 3, when you delete 3 then insert again, the id result is 4. And when you try to delete 2, the id result when you try insert again is 5.
Related
Iam using a table in Mysql database and here there is a field called as First_Seen and Last_Seen and one of the field ID is marked as primary Key.
Now suppose my record is like this
12445555555|1|4444444855|2017-03-09 15:02:55|abc|134|M|SOME_RANDOM_NAME
Out of these 1244555555 field is made primary key.
SO if I try to insert this record into database it is inserting properly with both first_seen and last_seen as 2017-03-09 15:02:55.
But whenever the script executes the same command after 10 min (say) because the id is made primary key,the next record with different time like this is not inserted.
12445555555|1|4444444855|2017-03-09 15:12:55|abc|134|M|SOME_RANDOM_NAME
So all I wanted to do instead of inserting duplicate record into database I want to update the last_seen field.Any suggestions on this.Because even the script executes the same record n no of times it won't be reflected in database.
This is the db_insert.py script which takes the record from the csv file and extract the fields and insert into db
time = record[6]
try:
cursor = connection.cursor()
# Trying to create a new record
sql = "INSERT IGNORE INTO `my_table` (`ID`,`F1`,`F2`,`First_Seen`,`Last_Seen`,`F3`,`F4`,`F5`,`F6`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,(id,f1,f2,time,time,f3,f4,f5,f6))
connection.commit()
finally:
connection.rollback()
connection.close()
All i wanted is whenever the duplicate entry occurs matching the id field then i need to replace the time with the time field in the current row and put it in last_seen.
This is what iam expecting.
12445555555|1|4444444855|2017-03-09 15:02:55|2017-03-09 15:12:55abc|134|M|SOME_RANDOM_NAME|something_else
Use ON DUPLICATE KEY UPDATE
INSERT INTO table (id, column1, column2)
VALUES(1, 'inserted value1', 'inserted value2') ON DUPLICATE KEY UPDATE column1="updated value 1", column2='updated value 2'
I'm using REPLACE INTO to update the row where mod_id is the unique/primary key. I wanted to know the mysql_inserted_id() if it was inserted.
I tried this:
$query_2 = $DB->query('REPLACE INTO mods (mod_id, group_id, css) VALUES (0, 4585, "css string")');
$inserted_id = mysql_insert_id();
But I keep getting $inserted_id of 0 even if an insert happend.
I think, its better to use INSERT... ON DUPLICATE KEY UPDATE. The reason being REPLACE always delete the old row optionally and then insert new row. While INSERT...ON DUPLICATE KEY UPDATE, tries to update the existing row as far as possible (based on primary or unique keys). And you can last_insert_id()
if I use this SQL:
UPDATE formulare SET EV_id=59, EV_status=5 WHERE EV_id=57 AND ID_uziv=12;SELECT LAST_INSERT_ID();
I will get 0 as last insert id.
I'm using php mysqli_insert_id and here is said that:
The mysqli_insert_id() function returns the ID generated by a query
on a table with a column having the AUTO_INCREMENT attribute.
If the last query wasn't an INSERT or UPDATE statement
or if the modified table does not have a column with the AUTO_INCREMENT attribute,
this function will return zero.
my table formualre has auto increment column, so I don't know wher the problem is
LAST_INSERT_ID() won't work if no new auto increment value was created.
The solution is something like this:
UPDATE formulare
SET EV_id=LAST_INSERT_ID(59),
EV_status=5
WHERE EV_id=57
AND ID_uziv=12;
SELECT LAST_INSERT_ID();
Note: I guess, that EV_id is the auto_increment primary key.
Otherwise you should do a query like:
UPDATE formulare
SET key_col = LAST_INSERT_ID(key_col),
EV_id=59,
EV_status=5
WHERE EV_id=57
AND ID_uziv=12;
SELECT LAST_INSERT_ID();
From the documentation :
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
As your update didn't create a new record, it didn't generate any AUTO_INCREMENT value.
UPDATE query updates the existing record, it doesn't return any new ID.
mysqli_insert_id retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
There was no INSERT query, that's the reason, you won't get any Id after executing UPDATE query.
For more info, refer mysql_insert_id
How do you set allow mySQL to auto increment a row in mySQL when using php? I have set the link_id column as auto_increment using phpMyAdmin but I do not know how to get the row to auto increment when using PDO.
$preparedStatement = $con->prepare('INSERT INTO link (link_id, category, link_desc, link_url) VALUES (:link_id, :category, :link_desc, :link_url)');
$preparedStatement-> execute(array(':link_id' => **AUTO INCREMENT Field in mySQL**, ':category' => $category,':link_desc' => $link_desc,':link_url' => $link_url));
Thanks for the help in advance!
You don't have to do anything special with PHP, but there are several ways in MySQL. One is to use a falsey value or null:
INSERT INTO link (<columns>) VALUES (null, category...
Just exclude the parameter in PHP.
You can also specify columns to insert, and if you leave off the auto_increment key, it gets auto incremented:
INSERT INTO link (category, link_desc...)
You can fill the AUTO_INCREMENT column at INSERT statement with any value ...
MySQL automatically will override AUTO_INCREMENT column value that are defined into your statement and handle with new value correctly.
In console mode it generates a warning if the value wasn't set correctly, but in PHP i think it will be ignored.
I have a following
Table1 : userid, who, share, date :: id is auto increment and primary key
I would like to build a query to check if record exist and insert new record if is empty.
How to build this in a single query and insert multiple records using a single query
data to inser ('a1','a2','a3','a4'), ('b1','b2','b3','b4'), ('c1','c2','c3','c4'), .......
Create UNIQUE index on column that you want to be unique
Use INSERT IGNORE to insert unique data and ignore not unique
You could use REPLACE statemement that works just like INSERT only it doesn't do anything if the row already exists:
REPLACE INTO table ...
http://dev.mysql.com/doc/refman/5.0/en/replace.html
You should take careful look at mysql INSERT INTO documentation.
How to insert "on no exists" is simple. Let's say you want combination of user,who,share to be unique and use latest date. Update your table and create UNIQUE KEY on those fields:
ALTER TABLE Table1 ADD UNIQUE KEY (user, who, share);
Normally inserting the same combination would cause error but using INSERT IGNORE (link above) would silently ignore error:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW());
You may also force key to update on insert:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW())
ON DUPLICATE KEY UPDATE date = VALUES(date);
And inserting multiple values at once, again the first link:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);