我正在尝试使用3个预准备语句插入和更新数据。发生了两个问题:
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();
答案 0 :(得分:1)