Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 550809
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:19:40+00:00 2026-05-13T11:19:40+00:00

This is my first time I am trying to make something seriously with relational

  • 0

This is my first time I am trying to make something seriously with relational db in MySQL and some kind of CMS created in PHP with CodeIgniter.
I came to the part where I have to insert some data in few many-to-many related tables.
In my code everything works fine (well, with just few minutes of testing), but I need some help with creating reusable function which will help me a lot to make all relations in my tables…

I tried to comment everything in my code, so all explanations are in there…

<?php
function add(){

 // This is what user posted in form.
 // There are two input fields:
 // name is always only one record
 // country can be a single record or array separated with " | " characters
 // I use CodeIgniter's $this->input->post instead of $_POST[]
 $name = $this->input->post('name');
 $countries = $this->input->post('country');

 // Inserting data to first table
 $data = array('firstName' => htmlentities($name)); // preparing array for inserting
 $insert_name = $this->db->insert('names', $data); // inserting with CodeIgniter's help
 $last_inserted_ID = $this->db->insert_id(); // getting last inserted ID

 // Inserting data to second table

 // Formatting of posted string of countries
 // Users can post strings similar to this:
 // "Austria"
 // "Austria |"
 // "Austria | "
 // "Austria | Australia"
 // "Austria | Australia |"
 // "Austria | Australia | "
 // and similar variations
 // What I need here is clear array with country names
 $separator = strpos($countries,"|"); // check for "|" character
 if ($separator === FALSE){ // if there is no "|" character in string
  $countries_array[] = $countries; // array is only one value (only one country)
 } else {
  $countries_array = explode(" | ", $countries); // explode my array
  if (end($countries_array) == ""){ // if last item in array is ""
   array_pop($countries_array); // eliminate last (empty) item
  }
 }

 // Now, this is the part I think I will use lots of times.
 // I would like to make this a separate function so I could use it in many places :)
 // I would pass to that function few values and I would use one of them
 // to call different functions in this same class.
 // I guess I should pass data ($countries_array) and function names I wish to call?????? This is problematic part for my brain :))
 // Check the comments below...
 for ($i = 0; $i < sizeof($countries_array); $i++){
  $insertIDS = array(); // this will be an array of IDs of all countries
  $tempdata = $this->get_countries($countries_array[$i]); // query which looks if there is a country with specific name
                // Right here, instead of calling $this->get_countries
                // I would like to call different functions, for example
                // $this->get_links($links_array[$i])
                // or $this->get_categories($categories_array[$i])
                // etc.
  if(sizeof($tempdata) != 0){ // so, if a record already exists
   foreach ($tempdata as $k => $v){
    $insertIDS[] = $k; // insert those IDs in our array
   }
  } else { // and if a record does not exist in db
   $this->add_country($countries_array[$i]); // add it as a new record...
               // This is also one of the places where I would call different functions
               // for example $this->add_link($links_array[$i])
               // or $this->add_categories($categories_array[$i])
               // etc.
   $insertIDS[] = $this->db->insert_id(); // ...get its ID and add it to array
  }

  // Finally, insert all IDs into junction table!
  foreach ($insertIDS as $idKey => $idValue){
   $this->add_names_countries($last_inserted_ID, $idValue); // Another place for calling different functions
                  // example $this->add_names_links($last_inserted_ID, $idValue)
                  // etc.
  }
 }

}
?>

Well, looking at this code now, I see that I could put that formatting part also in that function, but that’s not so much important right now…

Thank you very very much for any help with this!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:19:40+00:00Added an answer on May 13, 2026 at 11:19 am

    The preferred way of doing this is to use a Table Data Gateway. Instead of

    $this->db->insert('countries', $data);
    

    you create classes for each Table in your database. Each table encapsulates CRUD logic into the class, e.g.

    class Countries
    {
        $protected $_db;
    
        public function __construct($db)
        {
            $this->_db = $db;
        }
    
        public function save(array $countries)
        {
            $this->db->insert('countries', $countries);
        }
    
        // ... other methods
    }
    

    In addition, I suggest to use transactions for this kind of work because all that stuff belongs together and you likely do not want to insert any data, if one of the queries fails. I don’t know how CodeIgnitor handles transactions, but basically, you should do it this way then:

    $this->db->startTransaction();          // like try/catch for databases
    $countries = new Countries($this->db);
    $countries->save($countryData);
    $links = new Links($this->db);
    $links->save($linkData);
    // ...
    if($this->db->commit() === false) {     // returns true when no errors occured
        $this->db->rollback();              // undos in case something went wrong
    }
    

    While this does not answer your question how to dynamically call a function (call_user_func() could do this), doing it like suggested above makes your code much more maintainable.

    Your question is a bit vague as to if you want to run all the functions in a sequence or just want to interchange depending on what the user submitted. For the first case, use the transaction approach. For the second case, you would simply instantiate the appropriate class and call the save method.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 281k
  • Answers 281k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer So whenever there are that many stack frames, it means… May 13, 2026 at 3:46 pm
  • Editorial Team
    Editorial Team added an answer I'd rather use var_dump() instead of print to display the… May 13, 2026 at 3:46 pm
  • Editorial Team
    Editorial Team added an answer Use DirectoryInfo.GetFiles() and extract the data (Name, CreationTime, etc.) from… May 13, 2026 at 3:46 pm

Related Questions

Disclaimer: This is my first time writing unit tests...be gentle! :) I am trying
Scenerio: I'd like to run commands on remote machines from a Java program over
I'm trying to use the Class methods of prototype.js to manage my object hierarchy
I am running a MVC 2 Preview and this is my first time trying
I am trying to make it easy form my end users to search through

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.