gpt4 book ai didi

php - Yii2 如何使用 PDO 执行两条语句?或其他方式

转载 作者:行者123 更新时间:2023-11-28 23:37:12 25 4
gpt4 key购买 nike

我想创建数据库并在同一个数据库中导入数据。但是我没有运气就尝试过。

Action

public function actionRestore($id = null)
{
$list = $this->getFileList();
$file = $list[$id];
if(isset($file))
{
$transaction = Yii::$app->db->beginTransaction();
try{

$sql = 'DROP DATABASE IF EXISTS '.$this->getDbName().';CREATE DATABASE '.$this->getDbName();
$sqlFile = $this->path . basename($file);
Yii::$app->db->pdo->prepare($sql,$this->execSqlFile($sqlFile));
if(Yii::$app->db->pdo->exec())
{
$transaction->commit();
Yii::$app->session->setFlash('success', 'Backup Restored Successfully');
return $this->redirect(['index']);
}
$transaction->rollback();
}
catch(\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', "Backup not Restored. <br>".$e->getMessage());
return $this->redirect(['index']);

}
}
}

我不确定 execSqlFile() 方法:

public function execSqlFile($sqlFile)
{
$flag = false;
if (file_exists($sqlFile))
{
$sqlArray = file_get_contents($sqlFile);

$cmd = Yii::$app->db->createCommand($sqlArray);
try {
$cmd->execute();
$flag = true;
}
catch(Exception $e)
{
$flag = false;
throw new \yii\db\Exception($e->getMessage());

}

}
return $flag;

}

1) getDbName() 获取数据库名称。
1) getFileList()execSqlFile() 中获取要执行的文件。

我没有收到任何错误或成功或失败的消息。
我想将两者合并为一个 preparedStatement,但不知道我在这里遗漏了什么。

最佳答案

我找到了我需要使用 shell_exec 的解决方案:

public function execSqlFile($sqlFile)
{

if (file_exists($sqlFile))
{

$database=array();
$db=Yii::$app->db;
$database=explode(";",$db->dsn);
$dbname=explode("=",$database['1']);
$output = shell_exec('mysql -u '.$db->username.' -p'.$db->password.' '. $dbname['1'] .'< '.$sqlFile);
}
return $output;

}

关于php - Yii2 如何使用 PDO 执行两条语句?或其他方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com