2

Hi i am trying to insert data in database but $wpdb->insert insert two rows.

my code for insert data is

global $wpdb;
    $tablename = $wpdb->prefix . '<TABLE NAME>';
 for ($i = 0; $i < sizeof($emails); $i++) {

                $data = array("post_id" => $post_id,
                    "user_id" => $user_id,
                    "email" => $emails[$i], 
                    "status" => 1
                    );
                     $wpdb->insert($tablename, $data);

        }

size of $emails is 1 (if i am inserting one email id).

Where am i making mistake please let me know.

  • As far I know, $wpdb->insert() is intended to insert columns (one or more) in one row, you can not use it to insert data in two rows. – cybmeta Oct 28 '15 at 12:46
  • 1
    Please show more of your code, this one looks fine to me – M-R Oct 28 '15 at 12:48
  • i am trying to insert only one row but this function is inserting two rows into the database. – Bushra Shahid Oct 28 '15 at 12:49
  • @M-R Just Edited my code please review it. – Bushra Shahid Oct 28 '15 at 12:54
  • Have you tried pulling it out of the loop to make sure its not the loop? – M-R Oct 28 '15 at 12:57
1

Try something like this

function insert_data_into_table () {
        global $wpdb;
        $table_name = $wpdb->prefix . "your_table_name";

        //Check if table exists
        if($wpdb->get_var("show tables like '$table_name'") != $table_name) :

            //if not, create the table   
            $sql = "CREATE TABLE " . $table_name . " (
            (...)
            ) ENGINE=InnoDB;";

            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        else:
          foreach($emails as $mail):
              $insert = "INSERT INTO  " . $table_name . "
                (post_id, post_id, email, post_id) 
                VALUES ($post_id, $user_id, email['content'], 1);"
              $results = $wpdb->query( $insert );
          endforeach;
        endif;
    }

I'm assuming that $email is an array containing some data? If you want to save the entire array, then you should serialize() the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.