Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save techslides/192e1e034c81dddfa024851f07693f72 to your computer and use it in GitHub Desktop.
Save techslides/192e1e034c81dddfa024851f07693f72 to your computer and use it in GitHub Desktop.
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;
}
}
?>
@techslides
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment