Created
July 12, 2016 14:36
-
-
Save techslides/192e1e034c81dddfa024851f07693f72 to your computer and use it in GitHub Desktop.
INSERT on duplicate update PHP function for WordPress multiple or batch operation
This file contains hidden or 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
Read more: http://techslides.com/how-to-insert-or-update-multiple-items-in-mysql-and-wordpress