简体   繁体   中英

How to insert to a database and fetch the inserted record in one query?

Let's say you're making a CodeIgniter model's function which creates a user.

function create($data){
 $sql = "INSERT INTO people (fname,lname,age,location) VALUES(?,?,?,?)";
 $this->db->query($sql, $data);
}

function get($id){
 $sql = "SELECT * FROM people WHERE id = ? LIMIT 1";
 return $this->db->query($sql, array($id));
}

You want create() to create the user but return the same thing as get() as an associative array containing the user id and the other inserted info.

Obviously this could be done by making an array containing the $data elements. But think about a lot of fields.. it makes the code ugly and unsecure to modify because you'll deal with numerical arrays not associative.

Is there any way for the MySQL to return the inserted record with the id without having to query again using SELECT for better performance and neat looking code?

you could wrap the whole thing ( INSERT plus SELECT ) in a procedure, which would save you a callout to the database, and at the same time ensuring you read exactly what exists in the database (for eg autoincrement columns or defaulted values). But procedures aren't everybody's cup of tea.

In MySQL, no, there's no way to do what you want. Some databases (at least PostgreSQL) support a INSERT... RETURNING syntax, which allows this. Unfortunately, you will either have to re-query the newly inserted row, or mangle a return value out of the input value in your client code.

You can't insert and return the row in the same query with MySQL.

But you can get the last inserted id (I'm guessing the id field is autogenerated) with ->insert_id . You can use that to call get from your create function.

As @Flimzy said you cannot do it in one query ala Postgres with its RETURNING clause.

Your best bet is to use MySQL's LAST_INSERT_ID() which is guaranteed to return the newly created record's ID and its scoped to the current session so there is no issue of getting a race condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM