Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
INSERT on duplicate update PHP function for WordPress multiple or batch operation
<?php
//based on Wordpress Multiple Insert https://github.com/mirzazeyrek/wordpress-multiple-insert
function wp_insert_update_rows($row_arrays = array(), $wp_table_name) {
global $wpdb;
$wp_table_name = esc_sql($wp_table_name);
$update = "";
$query = "";
$query_columns = "";
$query. = "INSERT INTO {$wp_table_name} (";
foreach($row_arrays as $count => $row_array) {
if ($count == 0) {
$vv = "(";
} else {
$vv. = ",(";
$c = 0;
}
foreach($row_array as $key => $value) {
if ($count == 0) {
if ($query_columns) {
$query_columns. = ",".$key.
"";
$update. = ", $key=VALUES($key)";
if (is_null($value)) {
$vv. = ",NULL";
} else {
$vv. = ",'$value'";
}
} else {
$query_columns. = "".$key.
"";
$update. = "$key=VALUES($key)";
if (is_null($value)) {
$vv. = "NULL";
} else {
$vv. = "'$value'";
}
}
} else {
if ($c == 0) {
if (is_null($value)) {
$vv. = "NULL";
} else {
$vv. = "'$value'";
}
} else {
if (is_null($value)) {
$vv. = ",NULL";
} else {
$vv. = ",'$value'";
}
}
$c++;
}
}
$vv. = ")";
}
$query. = " $query_columns ) VALUES ".$vv;
$query. = " ON DUPLICATE KEY UPDATE ";
$query. = $update;
$doit = $wpdb - > query($query);
if ($doit) {
return true;
} else {
return false;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment