【发布时间】:2020-06-20 00:43:24
【问题描述】:
我在 mysql 中有一个表,假设:
ID - year - month
我在 year 和 month 上放置了一个 unique_constraint。这样一年就不可能有两个相同的月份。
ID 用于检索年份和月份的组合。假设我们有以下值:
ID - year - month
1 - 20 - 1
2 - 20 - 2
3 - 20 - 5
那么ID 3 将是 2020 年 5 月。但是,此表是动态构建的。我上传了具体的数据,需要插入所有年月的组合。
首先我使用 MySQL 突击队 REPLACE INTO,因为我认为它不会添加非唯一行。而且它不会添加非唯一行,但每次都会更新ID,导致我的外键搞砸了。
我该如何解决这个问题?只使用INSERT?由于 unique_constraint,插入将失败并返回错误。
现在我已经这样修复它了:
$conn = new mysqli(HOST, USER, PASS, DTBS);
$stmt = $conn->prepare("SELECT ID FROM periods WHERE month=? AND year=?");
$stmt->bind_param("ii", $month_, $year_);
$month_ = $month;
$year_ = $year;
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$rows = $stmt->num_rows;
$stmt->close();
if ($rows == 0) {
$stmt = $conn->prepare("INSERT INTO periods (year, month) VALUES (?, ?)");
$stmt->bind_param("ii", $year_, $month_);
$year_ = $year;
$month_ = $month;
$stmt->execute();
$stmt->close();
}
$conn->close();
【问题讨论】:
-
$stmt->num_rows在这里不起作用。先获取结果 -
@Dharman 我正在提取,
$stmt->fetch()? -
我的意思是你需要打电话给
get_result()或store_result() -
@Dharman 哦,是的,你是对的!谢谢。
-
如果您只是从 PHP 开始,那么我建议您学习 PDO 而不是 mysqli。这更容易
标签: php mysql sql sql-update sql-insert