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 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
idfield is autogenerated) with->insert_id. You can use that to callgetfrom yourcreatefunction.