2010-08-22 61 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

+0

這會阻止我添加或更新表格行嗎? – help 2010-08-22 11:03:03

+0

不,它告訴MySql你想要插入一行,但是如果它已經存在(根據主鍵確定,在這種情況下可能應該是'category_id' +'post_id'),它不應該嘗試插入新記錄,而是更新現有記錄。您通常會在查詢的更新部分更新列'updated_at'或類似內容。 – troelskn 2010-08-22 11:27:04

+0

我想停止添加或更新具有重複值的表格行。 – help 2010-08-22 11:48:50

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 2010-08-22 11:50:10

+0

你可以發佈你在這裏使用的代碼嗎? – 2010-08-22 12:00:01

+0

新發布的代碼並不是你的代碼的完全匹配,而是我在正確地知道嘗試新事物的時候。 – help 2010-08-22 12:15:02

1

當你使用的mysqli您應該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(); 

注:我也用INSERT忽略,所以插入會失敗默默如果關鍵是存在的。