2

I have a table like

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

I want insert some value to name column like

id|name
1 |1_myvalue
2 |2_myvalue
...

This table has multi users can insert to that. What can I do to make that thanks

$r = mysqli_query($conn, "INSERT INTO `test`(`name`) VALUES ('_myvalue')");
9
  • auto increment value is generated only at the time of insert so you cannot get it before insert.but there is a workaround for you check this post (mysql, php) How to get auto_increment field value before inserting data? Commented Aug 14, 2013 at 3:56
  • possible duplicate of stackoverflow.com/questions/2251463/… Commented Aug 14, 2013 at 3:56
  • Save the record, get the inserted record's id, update it Commented Aug 14, 2013 at 3:56
  • There's no safe way to do it! The most you could do is obtaining the latest registered id by calling last_insert_id() + 1 and locking table before you record a new record. Commented Aug 14, 2013 at 3:57
  • Why is there no safe way to do it? there are many ways to do it Commented Aug 14, 2013 at 4:06

1 Answer 1

4

Simple workaround:
Save the record, get the inserted record's id, update it to the proper value

$r = mysqli_query($conn, "INSERT INTO `test`(`name`) VALUES ('myvalue')");
//1. save the record

$id=mysqli_insert_id($conn));
//2.  get it's id

mysqli_query($conn, "UPDATE `test` set `name` = $id"."'_myvalue' where id=$id limit 1");
//3. update the record appending correct id to the value as desired
Sign up to request clarification or add additional context in comments.

4 Comments

That's working But, if multi users insert at the same time or another way, is that correct?
Yes why not? for most of the active website where are always multiple users doing stuff at the same time, that doesn't confuse MySQL into believing things otherwise. Why complicate things
b/c I want store my upload file, and the id is sole then the uploaded file will not coincidence :) thanks u
Shouldn't be a problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.