2010-08-22 5 views
1

배열에서 값을 확인하여 데이터베이스에 있는지 여부를 데이터베이스에서 다시 확인할 수 있는지 궁금합니다. 어떻게하면 PHP & MySQL을 사용하여이 작업을 수행 할 수 있습니까?PHP 및 MySQL 질문

PHP 코드.

for ($x = 0; $x < count($cat_id); $x++){ 
    $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())"; 
} 

수정 PHP 코드.

if(isset($cat_id)){ 

     for($x = 0; $x < count($cat_id); $x++){ 
      $check_query = mysqli_query($mysqli,"SELECT category_id FROM posts_categories WHERE category_id = '" . $cat_id[$x] ."' AND post_id = '" . $post_id . "'"); 

      if ($check_query == TRUE) { 
       unset($cat_id[$x]); 
      } 
     } 


     for($x = 0; $x < count($cat_id); $x++){ 
      $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())"; 
     } 
    } 

답변

1

INSERT .. ON DUPLICATE UPDATE을 사용할 수 있습니다. 당신은 당신이 probabaly

$stmt = $mysqli->prepare("INSERT IGNORE INTO posts_categories (category_id, post_id, date_created) VALUES (?, ?, ?)"); 

// Should use a prepared statement here. 
foreach ($categories as $key => $cat) { 

    // Bind params 
    $stmt->bind_param('iis', $cat, $post_id, 'NOW()'); 

    // Exectute the query 
    $stmt->execute(); 
} 

// Close the connection! 
$mysqli->close(); 

주 (보안 및 성능 측면 모두에서) 준비된 문을 사용한다 mysqli

+0

이로 인해 테이블 ​​행을 추가하거나 업데이트 할 수 없습니까? – help

+0

아니요, MySql에 행을 삽입하라고 알려주지 만 이미 존재하는 경우 (기본 키 (이 경우 'category_id' +'post_id'이어야 함)) 결정된대로 행을 삽입하려고 시도해서는 안됩니다 새 레코드가 아니라 기존 레코드를 업데이트합니다. 일반적으로 쿼리의 업데이트 부분에서'updated_at' 또는 유사한 열을 업데이트합니다. – troelskn

+0

중복 값이있는 테이블 행을 추가하거나 업데이트하지 않으려합니다. – help

0
$sql = "SELECT * FROM your_table WHERE your_column='".$yourArray['value']."'"; 
if(!mysql_num_rows(mysql_query($sql))){ 
    // no rows so add it to the database... 
} 
+0

나를 위해 작동하지 않았다 : ( – help

+0

여기에 사용 된 코드를 게시 할 수 있습니까? –

+0

새로운 게시 된 코드는 코드의 정확한 일치하지 않습니다. 바로 내가 새로운 것을 시도하는 것을 알고 있습니다. – help

1

를 사용하는 것처럼 : 나는 또한 INSERT가 무시 사용하기 때문에 삽입이 자동으로하면 실패합니다 열쇠가 존재합니다.