我在谷歌上发现了一些东西,上面说 MySql 允许我做这样的事情:
$sql = "IF(EXISTS(SELECT api_key, username FROM credentials WHERE id = 0))
THEN UPDATE credentials SET api_key = ?, username = ? WHERE id = 0 ELSE
INSERT INTO credentials (api_key, username) VALUES (?, ?) END IF";
这是查询构成的功能:
protected function store_credentials($config_file_path = 'envato_credentials_config.json') {
$credentials_config = $this->get_envato_config($config_file_path);
$sql = "INSERT INTO credentials (api_key, username, last_update) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username), last_update = values(last_update)";
if ($stmt = $this->connect->prepare($sql)) {
$stmt->bind_param('ss', $credentials_config['API'], $credentials_config['User']);
$stmt->execute();
$stmt->close();
} else {
return false;
}
}
我可以做这样的事情吗?我是否清楚地理解了该语句,如果在这两列中找不到值,则将插入新值,否则只会更新?