<?php
class UpdateAll {
public static function execute($table, $where, $data) {
$sql = self::getSql($table, $where, $data);
if ($sql) {
}
return $sql;
}
public static function getSql($table, $where, $data) {
if (empty($table) || empty($where) || empty($data) || !is_array($where) || !is_array($data)) {
return false;
}
$where_string = self::where($where);
$update = self::update($data);
$set = self::set($where, $data);
if (!$update || !$set || !$where) {
return false;
}
return "UPDATE `{$table}` a JOIN ( {$update} ) b USING({$where_string}) SET {$set}";
}
protected static function where($where) {
$string = '';
foreach ($where as $value) {
$string .= '`' . $value . '`,';
}
return substr($string, 0, strlen($string) - 1);
}
protected static function update($data) {
if (!isset($data[0])) {
return false;
}
$array_keys = array_keys($data[0]);
$count = count($array_keys);
$string = '';
foreach ($data as $key => $value) {
if (count($value) != $count) {
return false;
}
$string2 = ' SELECT ';
foreach ($array_keys as $value2) {
if (!isset($value[$value2])) {
return FALSE;
}
$string2 .= "'".$value[$value2]."'" . ' AS `' . $value2 . '`,';
}
$string2 = substr($string2, 0, strlen($string2) - 1);
$string .= $string2 . ' UNION';
}
return substr($string, 0, strlen($string) - 5);
}
protected static function set($where, $data) {
if (!isset($data[0])) {
return false;
}
$array_keys = array_keys($data[0]);
foreach ($array_keys as $key => $value) {
if (in_array($value, $where)) {
unset($array_keys[$key]);
};
}
if (empty($array_keys)) {
return FALSE;
}
$string = '';
foreach ($array_keys as $value) {
$string .= 'a.`' . $value . '`=b.`' . $value . '` ,';
}
return substr($string, 0, strlen($string) - 1);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結