I am trying to insert and update data using 3 prepared statements. There are two problems happening:
1: The SELECT COUNT query checks for if the record exists with a LIMIT 1 and result stored in $check. However, the LIMIT 1 seems to be ignored such as when I have 3 rows matching the WHERE conditions in the SELECT COUNT, $check returns 3 instead of 1.
2: The if ( (int)$check < 1 ) statement works and whenever $check = 0, I see the output from my echo’s, however the $stmt_insert->execute(); and $stmt_total->execute(); are not actually inserting and updating the database.
But, when I comment out:
$stmt_check->execute();
$stmt_check->bind_result($check);
$stmt_check->fetch();
then the $stmt_insert and $stmt_total works and the rows are inserted and updated. I’m wondering if there’s a way to make all three statements work properly, for it seems some kind of conflict is occurring with my current set up. Thank you for your time.
Here is the full code:
$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();
1 Answer