2012-09-17 60 views
2

我有一個foreach語句循環瀏覽JSON數據並將內容插入到MySQL中。如果顯示$ author字符串的特定用戶名,我想跳過插入操作。下面的方法是好的還是在數據庫級別處理更好?什麼是跳過MySQL INSERT的正確方法

foreach ($response['data'] as $data) {  
     $id = $data['id']; 
     $created_time = $data['created_time']; 
     $thumbnail = $data['images']['low_resolution']['url']; 
     $author = $data['user']['username']; 
     $caption = mysql_real_escape_string($data['caption']['text']); 
     $link = $data['link']; 
     $likes = $data['likes']['count']; 

     if ($author == 'USERNAME') { 
      mysql_close($con); 
     } else { 

     $query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash) VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')"; 
     $result = mysql_query($query) or die(mysql_error());   

    mysql_close($con); 
     } 
    } 
+4

爲什麼在循環的每次迭代結束時關閉連接? –

回答

3

爲什麼在每次循環迭代時關閉SQL連接?

爲什麼不能簡單地做:

if ($author == 'USERNAME') 
    continue; // next iteration 

$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash) 
    VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')"; 
$result = mysql_query($query) or die(mysql_error()); 

BTW你應該參數綁定到你的查詢,或至少使用mysql_real_escape_string()否則將有包含值引號(目前的問題,你只能做它可變$標題,我想這$鏈接$縮略圖$用戶名可以包含單引號爲好)。

相關問題