0
我正在嘗試使用3個預處理語句插入和更新數據。有兩個問題發生:使用多個mysqli預處理語句時的問題
1:SELECT COUNT查詢檢查記錄是否存在LIMIT 1,結果存儲在$ check中。但是,LIMIT 1似乎被忽略,例如當我有3行與SELECT COUNT中的WHERE條件匹配時,$ check返回3而不是1.
2:if((int)$ check < 1)語句有效,每當$ check = 0時,我會看到echo的輸出,但是$ stmt_insert-> execute();和$ stmt_total-> execute();實際上並沒有插入和更新數據庫。
但是,當我註釋掉:
$stmt_check->execute();
$stmt_check->bind_result($check);
$stmt_check->fetch();
那麼$ stmt_insert和$插入和更新stmt_total工程和行。我想知道是否有一種方法可以使所有三種語句正常工作,因爲它似乎與我目前的設置發生了某種衝突。感謝您的時間。
下面是完整的代碼:
$user_id = 100;
$count = preg_match_all("#<li>(.*?)</li>#is", $html, $matches, PREG_SET_ORDER);
$stmt_check = $mysqli->stmt_init();
$stmt_check->prepare("SELECT COUNT(`user_id`) AS `check` FROM `ua` WHERE `ach_class` = ? AND `user_id` = ? LIMIT 1");
$stmt_check->bind_param('si', $ach_class, $user_id);
$stmt_insert = $mysqli->stmt_init();
$stmt_insert->prepare("INSERT INTO `ua` (`user_id`, `ach_class`, `time_log`) VALUES (?, ?, ?)");
$stmt_insert->bind_param('isi', $user_id, $ach_class, $ach_timestamp);
$stmt_total = $mysqli->stmt_init();
$stmt_total->prepare("UPDATE `ach` SET `total` = `total` +1 WHERE `ach_class` = ? LIMIT 1");
$stmt_total->bind_param('s', $ach_class);
for ($i = 0; $i < $count; $i++) {
$li_block = $matches[$i][1];
preg_match('#img/(.*?)_60.png#is', $li_block, $class_matches);
$ach_class = $class_matches[1];
$ach_class = substr($ach_class, 11, -11);
$ach_timestamp = time();
$stmt_check->execute();
$stmt_check->bind_result($check);
$stmt_check->fetch();
echo $ach_class.' --- Check = '.$check.'<br />';
if ((int)$check < 1) {
$stmt_insert->execute();
echo 'insert<br />';
$stmt_total->execute();
echo 'update<br />';
} else {
echo 'already present<br />';
}
}
$stmt_insert->close();
$stmt_check->close();
$stmt_total->close();