了解了,您想要同时(并发)执行多个SQL语句。在PHP中,我们可以使用多线程或异步操作来实现这一点。由于PHP本身是同步的,我们需要依靠外部工具如pthreads
来实现真正的并发执行。但是,对于MySQL来说,并行执行写操作可能导致数据不一致的问题。因此,稳妥的做法是使用事务来保证数据一致性。
这里提供一个使用事务的解决方案,虽然不是真正的并发执行,但是确保了数据的一致性:
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>批量替换词</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<form @submit.prevent="submitForm">
<label for="oldValue">替换前词:</label>
<input type="text" v-model="oldValue" id="oldValue" placeholder="输入要替换的词" default="替换前关键词" required>
<br>
<label for="newValue">替换后词:</label>
<input type="text" v-model="newValue" id="newValue" placeholder="输入替换后的词" default="替换后关键词" required>
<br>
<button type="submit">提交</button>
<button type="button" @click="clearFields">清空</button>
</form>
<div v-if="message">{{ message }}</div>
</div>
<script>
new Vue({
el: '#app',
data: {
oldValue: '替换前关键词',
newValue: '替换后关键词',
message: ''
},
methods: {
submitForm() {
const sqls = [
`UPDATE fa_ask_question SET title = REPLACE(title, '${this.escapeSql(this.oldValue)}', '${this.escapeSql(this.newValue)}') WHERE title LIKE '%${this.escapeSql(this.oldValue)}%'`,
`UPDATE fa_ask_question SET content = REPLACE(content, '${this.escapeSql(this.oldValue)}', '${this.escapeSql(this.newValue)}') WHERE content LIKE '%${this.escapeSql(this.oldValue)}%'`,
`UPDATE fa_ask_question SET content_fmt = REPLACE(content_fmt, '${this.escapeSql(this.oldValue)}', '${this.escapeSql(this. newValue)}') WHERE content_fmt LIKE '%${this.escapeSql(this.oldValue)}%'`
];
fetch('execute_sql.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ sqls })
})
.then(response => response.json())
.then(data => {
this.message = data.success ? '更新成功!' : '更新失败:' + data.error;
})
.catch(err => {
console.error(err);
this.message = '请求错误,请稍后再试。';
});
},
escapeSql(val) {
return val.replace(/[\\"']/g, '\\$&');
},
clearFields() {
this.oldValue = '';
this.newValue = '';
}
}
});
</script>
</body>
</html>
execute_sql.php
)execute_sql.php
<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"), true);
require_once 'database.php'; // 包含数据库连接配置文件
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
die(json_encode(['success' => false, 'error' => "连接失败: " . $conn->connect_error]));
}
$conn->begin_transaction();
try {
foreach ($data['sqls'] as $sql) {
if (!$conn->query($sql)) {
throw new Exception("SQL执行错误: " . $conn->error);
}
}
$conn->commit();
echo json_encode(['success' => true]);
} catch (Exception $e) {
$conn->rollback();
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
$conn->close();
?>
database.php
)database.php
<?php
// 数据库服务器地址
define('DB_SERVER', 'localhost');
// 数据库用户名
define('DB_USER', 'your_username');
// 数据库密码
define('DB_PASS', 'your_password');
//