去除旧版更新数据库结构方法

This commit is contained in:
WispX
2020-03-14 19:42:06 +08:00
parent 3915f83883
commit 7effc2c6d6
2 changed files with 1 additions and 104 deletions
-104
View File
@@ -166,108 +166,4 @@ EOT;
]);
return $this->fetch();
}
public function update($start = 0)
{
try {
$user = false;
if (Session::has('uid')) {
$user = Users::get(Session::get('uid'));
if (!$user) {
Session::delete('uid');
}
}
if (!$user || !$user->is_admin) {
$this->redirect(url('/'));
}
$path = Env::get('root_path') . 'update.sql';
$file = @file_get_contents($path);
if (!$file) {
$this->redirect(url('/'));
}
$code = 0;
$msg = null;
if ($start == 1) {
if ($file) {
$config = Config::pull('db');
// 替换sql关键字
$file = str_replace([
'{database}'
], [
$config['database']
], $file);
$mysqli = new \mysqli(
$config['hostname'],
$config['username'],
$config['password'],
$config['database'],
$config['hostport']
);
if ($mysqli->connect_errno) {
$mysqli->close();
throw new Exception($mysqli->connect_error);
}
$mysqli->autocommit(false);
$mysqli->select_db($config['database']);
$mysqli->query("SET NAMES utf8");
// 新建表字段
$tableFields = Config::pull('table');
foreach ($tableFields as $table => $fields) {
foreach ($fields as $field => $sql) {
$fetchFields = $mysqli->query("DESCRIBE `{$table}`;");
// 判断字段是否已存在
$flag = true;
foreach ($fetchFields as $fetchField) {
if ($field == $fetchField['Field']) {
$flag = false;
}
}
if ($flag) {
if (!$mysqli->query($sql)) {
throw new Exception($mysqli->error);
}
}
}
}
foreach (explode(';', $file) as $value) {
if ($value && !ctype_space($value)) {
if (!$mysqli->query($value . ';')) {
throw new Exception('<p>数据导入失败!</p><p>错误信息:<br/>' . $mysqli->error . '</p><p>sql语句:<br/>' . $value . '</p>');
}
}
}
$mysqli->commit();
$mysqli->autocommit(true);
$mysqli->close();
}
$code = 1;
$msg = '更新成功,返回<a href="/">首页</a>';
// 删除sql文件
@unlink($path);
if (file_exists(Env::get('root_path') . 'install.sql')) {
@unlink(Env::get('root_path') . 'install.sql');
}
}
} catch (Exception $e) {
$mysqli->rollback();
$mysqli->close();
$code = 0;
$msg = $e->getMessage();
}
$this->assign([
'code' => $code,
'msg' => $msg
]);
return $this->fetch();
}
}
@@ -8,6 +8,7 @@
namespace app\index\controller\admin;
use app\common\model\Config;
use think\Db;
use app\common\model\Images;
use think\Exception;