简体   繁体   中英

Insert all rows of an array into MySql table - Codeigniter-related

I'm trying to enter 100 email addresses separated by ';' and store them in MySql table. What I've tried so far is:

    $recipient_raw = $this->input->post('recipient'); //get the 100 emails in $recipient_raw
    $recipient_array=explode(';', $recipient_raw);  //explode them into an array
    $title = $this->input->post('title');
    $body = $this->input->post('body');

    foreach($recipient_array->result() as $row): 
    $recipient=array(
    'email'=>$row->email             //looping through each email; seems I should not use $row->email since there's no title for them
    );

    $this->db->insert('eamil_send',$this->db->escape($recipient));
    endforeach;

I'm running this on CodeIgniter PHP. Error msg is on line foreach($recipient_array->result() as $row):, where it says: Call to a member function result() on a non-object

Any advice is appreciated! Thanks!

result(), is an active record function for converting a database result object. You are creating a standard array.

$batch = array();
foreach($recipient as $row){
    $batch[] = array(
        'email' => $row
    );
}
$this->db->insert_batch('email_send', $batch);

That should do what you're trying to accomplish.

The error message is pretty much self explanatory..

  • In the 2nd line of your code you declared $recipient_array as an Array(), not an object. So, there's no "result" method available. Your loop should be

    foreach($recipient_array as $row)

  • On a side note, you probably shouldn't be executing db operations inside a loop (especially, for 100 operations!). Instead, you should save all the queries in one big query string and execute at the end.

If you want your 100 email address be separate by ',' you should use implode(glue, pieces) instead of explode() function. Like on email address that you want to insert.

$recipient_raw = array();
$recipient_raw[] = $this->input->post('recipient');

foreach ($recipient_raw as $value) {

        $tem_arr = implode(',', $value);
    }

$this->db->insert('eamil_send',$this->db->escape($tem_arr));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM