哎,因为图片服务器的网址变了,所以让把数据库里所有表所有字段的数据里的旧网址替换成新网址,所以就只能写了这么一个代码,貌似效率还不错,20多W的数据量,只用了13秒,好的代码不需要太多的文字来解释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
<?php
class
TestAction
extends
Action{
private
$old_str
=
''
;
private
$new_str
=
''
function
index(){
set_time_limit(0);
$tableList
=
$this
->getTables();
foreach
(
$tableList
as
$k
=>
$v
){
//如果没有数据则直接执行
if
(
$this
->getDataList(
$v
)){
//获取表字段
$fieldList
=
$this
->getFieldInfo(
$v
);
$list
=
$this
->db_replace(
$v
,
$fieldList
);
dump(
$list
);
}
}
}
private
function
getTables(){
$model
=D(
'Api'
);
$tableList
=
$model
->getTables();
//获取所有表名
//处理表名称
foreach
(
$tableList
as
$k
=>
$v
){
if
(
substr
(
$v
,0,
strlen
(C(
'DB_PREFIX'
)))!==C(
'DB_PREFIX'
))
unset(
$tableList
[
$k
]);
else
$tableList
[
$k
]=
str_replace
(C(
'DB_PREFIX'
),
''
,
$v
);
}
return
$tableList
;
}
//获取字段信息
private
function
getFieldInfo(
$table
){
$model
=D(
$table
);
$list
=
$model
->getDbFields();
return
$list
;
}
//查询表中是否有数据
private
function
getDataList(
$table
){
$model
=D(
$table
);
$list
=
$model
->select();
if
(
$list
)
return
true;
else
return
false;
}
//执行替换
private
function
db_replace(
$table
,
$field
){
$tableName
=C(
'DB_PREFIX'
).
$table
;
$field
=
$this
->db_filter(
$field
);
if
(!
empty
(
$field
)){
foreach
(
$field
as
$k
=>
$v
){
$sql
=
"UPDATE `$tableName` SET `$v` = REPLACE ( `$v`, '$this->old_str', '$this->new_str' ); "
;
if
(M()->execute(
$sql
))
$ok
[]=
'替换完成,替换表为.'
.
$tableName
.
'|替换字段为'
.
$v
.
'<br />'
;
}
}
return
$ok
;
}
//字段过滤
private
function
db_filter(
$field
){
$in
=
array
(
'id'
,
'name'
,
'title'
,
'token'
,
'wecha_id'
,
'pid'
,
'level'
,
'uid'
);
foreach
(
$field
as
$k
=>
$v
){
if
(in_array(
$v
,
$in
)){
unset(
$field
[
$k
]);
}
}
return
$field
;
}
}
|
本文转自 3147972 51CTO博客,原文链接:http://blog.51cto.com/a3147972/1555169,如需转载请自行联系原作者