哎,因为图片服务器的网址变了,所以让把数据库里所有表所有字段的数据里的旧网址替换成新网址,所以就只能写了这么一个代码,貌似效率还不错,20多W的数据量,只用了13秒,好的代码不需要太多的文字来解释
<?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;
}
}