2012-01-21 8 views
0

3 개의 준비 문을 사용하여 데이터를 삽입하고 업데이트하려고합니다. 두 가지 문제가 발생합니다 :여러 mysqli 준비 문을 사용할 때의 문제

1 : SELECT COUNT 쿼리는 레코드가 LIMIT 1로 존재하고 $ check에 결과가 저장되어 있는지 확인합니다. 그러나 LIMIT 1은 SELECT COUNT의 WHERE 조건과 일치하는 행이 3 개있는 경우와 같이 무시되는 것 같습니다.

2 if ((int) $ check <) 문이 작동하고 $ check = 0 일 때마다 내 echo의 출력을 보지만 $ stmt_insert-> execute(); 및 $ stmt_total-> execute(); 실제로 데이터베이스를 삽입하고 업데이트하지 않습니다. 내가 주석

하지만, :

$stmt_check->execute(); 
$stmt_check->bind_result($check); 
$stmt_check->fetch(); 

다음은 $ stmt_insert 및 $가 stmt_total 작품과 행이 삽입 업데이트됩니다. 3 가지 문장을 모두 제대로 작동시키는 방법이 있는지 궁금합니다. 현재 설정 한 상태에서 충돌이 발생하고있는 것 같습니다. 시간 내 주셔서 감사합니다.

LIMIT 작동
$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
  1. ... 그것은 반환 된 행의 수를 제한하고, 하나의 필드 (단지 계산)으로 1 개 행을 반환하는에서 그 한계 때문에 : 여기

    는 전체 코드입니다 끝은 아무 래도 무의미합니다. 어쨌든 단일 결과를 반환하기 때문입니다. 또한 UPDATE 명령에 LIMIT 1이있는 이유는 무엇입니까?
  2. INSERT ON DUPLICATE KEY UPDATE을 사용하고 열에 UNIQUE 색인 ach_class, user_id를 작성하면 문제가 없습니다.
관련 문제