Home » Php » php – Inserting data in 2 different tables in database

php – Inserting data in 2 different tables in database

Posted by: admin February 25, 2020 Leave a comment


I have a code in Php which saves data in only one data-table called “sales”. I want to add another data-table called “all”. My goal is to save the data at the same time in 2 different data-tables. This is the part of code that I save data to the table called “sales” and where I want to also add table “all”.

    if ($this->db->insert('sales', $data)) {
        $sale_id = $this->db->insert_id();
        if ($this->site->getReference('so') == $data['reference_no']) {
How to&Answers:

I’d argue you ought to rethink your database schema, database normalisation is a topic you might find worthwhile reading up on too, the gist of it is that you should never store two copies of the same data within the same database (of course you should still keep backups)

Instead you should either combine the data from multiple tables upon retrieval using something like UNION ALL, or store them all in one table with some indication of what type of record it is, and filter them out with your query. Which one you choose will obviously depend on what your data looks like.