2015-04-05 18 views
1

我試圖根據其包含的團隊將我的文章連接到不同的團隊。目前,我有以下3個表:檢查文章是否包含團隊名稱

teams(id, name, shortname) 
news(id, title, text, url) 
contain(team_id, news_id) 

我的問題是那麼下面插入查詢後

mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')"); 

我要檢查變量$ full_text_strip包含球隊名的一個或短名稱,如果是它應該在剛剛創建的news_id和team_id中的包含表中創建一個新記錄。最簡單的方法是什麼?

回答

0

這是一個未經考驗的SQL解決方案:

<?php 
$query = "select name, shortname, id from teams"; 
$result = mysqli_query($con, $query); 
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 
    $ids[$row['id'][] = $row['name']; 
    $ids[$row['id']][] = $row['shortname']; 
} 
foreach($ids as $id => $teams) { 
    foreach($teams as $team) { 
     if(strpos($full_text_strip, $team) !== false) { 
      //mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')"); 
      echo 'We are inserting here because ' . $team . ' is present.'; 
     } 
    } 
} 
?> 

測試代碼:

<?php 
$title = 'this is input blue jays for the testing'; 
$ids = array(1 => array('blue jay', 'blues'), 2 => array('red sox', 'reds'), 3 => array('white sox', 'whites')); 
foreach($ids as $id => $teams) { 
    foreach($teams as $team) { 
     if(strpos($title, $team) !== false) { 
      echo 'Insert ' . $team . 'with id ' . $id; 
     } 
    } 
} 
+0

但我如何得到球隊ID在foreach循環? – 2015-04-05 20:58:18

+0

更新後,我在該字段的插入語句中沒有看到一列。 – chris85 2015-04-05 21:10:32