Welcome Guest, Not a member yet? Register   Sign In
$this->db->insert Within Loop
#1

[eluser]Jay Logan[/eluser]
Why doesn't this work? I don't get an error. But only 1 entry is inserted into the database. I did a print_r on the $events variable and there are about 25 items in it. I'm so confused.

Code:
function copy_events_for_template($meet_id, $template_id, $host_id)
    {
        $this->db->select();
        $this->db->from('meet_events');
        $this->db->where('meet_id', $meet_id);
        $get_events = $this->db->get();
        $events = $get_events->result_array();
        foreach ($events as $event)
        {
            $data['event_id'] = $event['event_id'];
            $data['gender'] = $event['gender'];
            $data['template_id'] = $template_id;
            $this->db->insert('meet_template_events', $data);
        }
    }
#2

[eluser]minhbu[/eluser]
try this code


foreach ($events as $k => $event)
{
$data['event_id'] = $event['event_id'];
$data['gender'] = $event['gender'];
$data['template_id'] = $template_id;
$this->db->insert('meet_template_events', $data);
}
#3

[eluser]TheFuzzy0ne[/eluser]
I'm guessing you are getting an error, but you can't see it as you've turned down the error reporting level. Can you confirm that this isn't the case?

I've tidied up your code a little. It may not make any difference, but it only took a few seconds, so I figured I should do it:
Code:
function copy_events_for_template($meet_id, $template_id, $host_id)
    {
        $this->db->where('meet_id', $meet_id);
        $events = $this->db->get('meet_events');

        foreach ($events->result_array() as $event)
        {
            $data['event_id'] = $event['event_id'];
            $data['gender'] = $event['gender'];
            $data['template_id'] = $template_id;
            $this->db->insert('meet_template_events', $data); // I think this line might be inserting over a row where the ID exists
        }
    }
#4

[eluser]xwero[/eluser]
Instead of inserting each row individually you better create a string of values.
Code:
$this->db->where('meet_id', $meet_id);
$events = $this->db->get('meet_events');

$values = array();

foreach ($events->result_array() as $event)
{
   $values[] = '('.$event['event_id'].','.$event['gender'].','.$this->db->escape($template_id).')';
}

if( ! empty($values))
{
   $this->db->query('INSERT INTO meet_template_events (event_id,gender,template_id) VALUES '.implode(',',$values));
}
$template_id is the only variable that needs escaping because the two others already come out of the database.

If your database is capable of better ways to query it, don't be afraid to drop the nice CI syntax.
#5

[eluser]Jay Logan[/eluser]
Fixed. Silly me didn't notice the table had unique index key on the template_id field. Thanks.




Theme © iAndrew 2016 - Forum software by © MyBB