how to insert data to two tables at the same time?
I have this problem in my system, i need to register a patient to the system, patients reference_number is used to make a reservation in the hospital. problem i got is when a patient is registered to the system a reservation is made at the same time, i need to update two tables, patient table and reservation table, i have to take the reference_number from the patient table and enter it to the reservation table.reference number must be taken from the database, and new one should be one increment than the old one. how to do this guys? i'm confused about this. :(
i'm develping the system using codeigni开发者_如何学Cter,php and mysql
regards, Rangana
I would think you could easily do it with two insert statements right after one another and use mysql_insert_id to fetch the id of the previous query. But this might not work for you if your tables are defined differently:
mysql_query('INSERT INTO patients [...]');
$patientId = mysql_insert_id();
mysql_query('INSERT INTO reservations [...]');
I'm a bit pushed for time this morning, so forgive me if that this is not a fuller explanation. I also know nothing about codeigniter, so hopefully it does support stored procdures.
In MySQL there is a LAST_INSERT_ID() function (see http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id)
You should be able to use this in a stored procedure to update the second table with the identity from the first.
Hope that helps.
Going on the vague information, you could do it like follows.
$this->db->insert('patients_records_tbl', $data);
$last_id = $this->db->insert_id();
$this->db->insert('other_tbl', array('patient_id' => $last_id));
I hope that vaguely covers it for you.
thomasmalt,JonRed and James Norman thanx guys for the great help
This is the code
$this->db->insert('patient',$data);
$sql = "SELECT LAST_INSERT_ID()";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_row($query);
$lastID = $row[0];
}
$this->db->insert('visit',$visit_data);
$data and $visit_data are the two arrays containing insert data, $visit_data contains the $lastID
hope you guys also can use this in the future :)
精彩评论