Forked from techslides/multiple-insert-on-duplicate-update.php
Last active
January 11, 2021 11:50
-
-
Save milanarandjelovic/35520924ef6bd2f6f24ffa21983a4be4 to your computer and use it in GitHub Desktop.
WordPress - INSERT on duplicate update PHP function for WordPress multiple or batch operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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