canyin-project/ybcy/controllers/admin/UpdateController.php
2024-11-01 16:07:54 +08:00

78 lines
2.7 KiB
PHP

<?php
namespace app\controllers\admin;
use Illuminate\Support\Facades\DB;
use Yii;
use yii\web\Controller;
class UpdateController extends Controller{
public $enableCsrfValidation = false;
function fieldexists($tablename, $fieldname){
$sql="SHOW COLUMNS FROM " . $tablename;
$fields=Yii::$app->db->createCommand($sql)->queryAll();
if (empty($fields)) {
return false;
}
foreach ($fields as $field) {
if ($fieldname == $field['Field']) {
return true;
}
}
return false;
}
function getField($sql){
$str=substr($sql,strrpos($sql ,"column")+7);
$field=explode(' ',$str)[0];
return $field;
}
function intercept_str($start,$end,$str)
{
if(empty($start)||empty($end)||empty($str))return "参数不正确";
$strarr=explode($start,$str);
$str=$strarr[1];
$strarr=explode($end,$str);
return $strarr[0];
}
public function actionSqlDumpLoad($sql){
if(strpos($sql,'CREATE') !==false){
$connection=Yii::$app->db;
$transaction=$connection->beginTransaction();
try {
$connection->createCommand($sql)->execute();
} catch(\Exception $e){// 如果有一条查询失败,则会抛出异常
echo $e->getMessage();die;
$transaction->rollBack();
}
}else{
if(strpos($sql,'INSERT') !==false){
Yii::$app->db->createCommand($sql)->execute();
}
if(strpos($sql,'truncate') !==false){
Yii::$app->db->createCommand($sql)->execute();
}
if(strpos($sql,'ADD') !==false){
$tablename=trim($this->intercept_str('TABLE','ADD',$sql));
}
if(strpos($sql,'modify') !==false){
$tablename=trim($this->intercept_str('TABLE','modify',$sql));
}
$fieldname=$this->getField($sql);
if($tablename&&$fieldname){
$bool=$this->fieldexists($tablename, $fieldname);
if(($bool&&strpos($sql,'ADD')==false) or (!$bool&&strpos($sql,'ADD')!==false)){
$connection=Yii::$app->db;
$transaction=$connection->beginTransaction();
try {
$connection->createCommand($sql)->execute();
} catch(\Exception $e){// 如果有一条查询失败,则会抛出异常
echo $e->getMessage();die;
$transaction->rollBack();
}
}
}
}
}
}