programing

워드프레스 $wpdb.여러 레코드 삽입

oldcodes 2023. 2. 23. 23:03
반응형

워드프레스 $wpdb.여러 레코드 삽입

Wordpress에서 다음 작업을 수행할 수 있는 방법이 있습니까?$wpdb->insert또는

$wpdb->query($wpdb->prepare)):

INSERT into TABLE (column1, column2, column3) 
VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3')

...기타

알았어, 알았어!

실제 값 및 플레이스홀더 어레이 설정

$values = array();
$place_holders = array();

첫 번째 쿼리:

$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";

그런 다음 추가할 값을 반복하여 적절한 배열에 삽입합니다.

foreach ( $_POST as $key => $value ) {
     array_push( $values, $value, $order_id );
     $place_holders[] = "('%d', '%d')" /* In my case, i know they will always be integers */
}

그런 다음 초기 쿼리에 다음 비트를 추가합니다.

$query .= implode( ', ', $place_holders );
$wpdb->query( $wpdb->prepare( "$query ", $values ) );

다음 방법으로 쿼리를 작성할 수도 있습니다.

$values = array();

// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
    $values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}

$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
$query .= implode( ",\n", $values );

저는 이 문제를 발견했고, 인정된 답변을 사용하여 더 향상된 기능을 구축하기로 결정했습니다.

/**
 * A method for inserting multiple rows into the specified table
 * 
 *  Usage Example: 
 *
 *  $insert_arrays = array();
 *  foreach($assets as $asset) {
 *
 *  $insert_arrays[] = array(
 *  'type' => "multiple_row_insert",
 *  'status' => 1,
 *  'name'=>$asset,
 *  'added_date' => current_time( 'mysql' ),
 *  'last_update' => current_time( 'mysql' ));
 *
 *  }
 *
 *  wp_insert_rows($insert_arrays);
 *
 *
 * @param array $row_arrays
 * @param string $wp_table_name
 * @return false|int
 *
 * @author  Ugur Mirza ZEYREK
 * @source http://stackoverflow.com/a/12374838/1194797
 */

function wp_insert_rows($row_arrays = array(), $wp_table_name) {
    global $wpdb;
    $wp_table_name = esc_sql($wp_table_name);
    // Setup arrays for Actual Values, and Placeholders
    $values = array();
    $place_holders = array();
    $query = "";
    $query_columns = "";

    $query .= "INSERT INTO {$wp_table_name} (";

            foreach($row_arrays as $count => $row_array)
            {

                foreach($row_array as $key => $value) {

                    if($count == 0) {
                        if($query_columns) {
                        $query_columns .= ",".$key."";
                        } else {
                        $query_columns .= "".$key."";
                        }
                    }

                    $values[] =  $value;

                    if(is_numeric($value)) {
                        if(isset($place_holders[$count])) {
                        $place_holders[$count] .= ", '%d'";
                        } else {
                        $place_holders[$count] .= "( '%d'";
                        }
                    } else {
                        if(isset($place_holders[$count])) {
                        $place_holders[$count] .= ", '%s'";
                        } else {
                        $place_holders[$count] .= "( '%s'";
                        }
                    }
                }
                        // mind closing the GAP
                        $place_holders[$count] .= ")";
            }

    $query .= " $query_columns ) VALUES ";

    $query .= implode(', ', $place_holders);

    if($wpdb->query($wpdb->prepare($query, $values))){
        return true;
    } else {
        return false;
    }

}

출처 : https://github.com/mirzazeyrek/wp-multiple-insert

$wpdb를 사용하여 여러 행을 삽입할 뿐만 아니라 기존 행을 업데이트해야 할 경우 다음 스니펫이 도움이 됩니다.이것은 @phillip이 위에서 제공한 최신 단편입니다.

$values = array();

// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
    $values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}

$values = implode( ",\n", $values );
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES {$values} ON DUPLICATE KEY UPDATE `quantity` = VALUES(quantity)";

조금 늦었지만 이렇게도 할 수 있어요.

    global $wpdb;
    $table_name = $wpdb->prefix . 'your_table';

    foreach ($your_array as $key => $value) {
          $result = $wpdb->insert( 
            $table_name, 
            array( 
              'colname_1' => $value[0], 
              'colname_2' => $value[1], 
              'colname_3' => $value[2], 
            ) 
          );
        }
  if (!$result) {
    print 'There was a error';
  }

별로 좋진 않지만, 당신이 뭘 하고 있는지 알고 있다면:

require_once('wp-load.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);  
@mysql_select_db(DB_NAME) or die();
mysql_query("INSERT into TABLE ('column1', 'column2', 'column3') VALUES 
                               ('value1', 'value2', 'value3'), 
                               ('otherval1', 'otherval2', 'otherval3'),
                               ('anotherval1', 'anotherval2', 'anotherval3)");

언급URL : https://stackoverflow.com/questions/12373903/wordpress-wpdb-insert-multiple-records

반응형