2013-03-22 58 views
0

我試圖將關聯的PHP數組(表)存儲到數據庫中。這是一個包含許多字段(大約30個字段)的大數組,並且我只想存儲6個這個數組的字段放在一個有6個字段的表中。此數組上的每一行都包含特定文章的信息。我想確保每篇文章只存儲一次(不重複),因此在存儲數據之前我需要檢查數據庫是否存在重複查詢。這是我的代碼無法正常工作。如果有人幫助我,我將不勝感激。將關聯的PHP數組存儲到數據庫中而不重複

<?php $results = $PubMedAPI->query($term, false); ?> 
<?php if (!empty($results)): ?> 
<?php 
    $con=mysqli_connect("localhost","root","","db"); 
    // Check connection 
    if (mysqli_connect_errno()) 
    { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
    foreach ($results as $result): 

     $pmid = $result['pmid']; 
     $title = $result['title']; 
     $authors = $result['authors']; 
     $journalabbrev = $result['journalabbrev']; 
     $year = $result['year']; 
     $abstract = $result['abstract']; 
     $fetched_articles = mysqli_query($con,"SELECT pmid FROM articles"); 

     while(($row = mysqli_fetch_array($fetched_articles))) { 
      if ($row['pmid'] == $pmid) { 
       echo "This record has already been stored into the database!"; 
      } else { 
       mysqli_query($con,"INSERT INTO articles (pmid, title, authors, journalabbrev, year, abstract) 
       VALUES ('$pmid', '$title', '$authors', '$journalabbrev', '$year', '$abstract')"); 
       echo "This record has been stored into the database!"; 
      } 
     } 
    endforeach; 
    mysqli_close($con); 
?> 
<?php endif; ?> 
+0

請問你的陣列是什麼樣子?請編輯您的問題並添加陣列 – michi 2013-03-22 23:37:19

回答

0

下面是一些未經測試的代碼做得更快:

$select = "SELECT pmid FROM articles WHERE pmid IN ("; 
foreach($result in $results) { 
    $select .= $result['pmid'] . ','; 
} 
$select = trim($select,',') . ")"; 


$existing_pmid = array(); 
while(($row = mysqli_fetch_array($select))) { 
    $existing_pmid[$row['pmid']] = 1; 
} 

foreach ($results as $result) { 
    if(isset($existing_pmid[$result['pmid']])) { 
     echo "This record has already been stored into the database!"; 
     continue; 
    } 

    $pmid = $result['pmid']; 
    $title = $result['title']; 
    $authors = $result['authors']; 
    $journalabbrev = $result['journalabbrev']; 
    $year = $result['year']; 
    $abstract = $result['abstract']; 

    mysqli_query($con,"INSERT INTO articles (pmid, title, authors, journalabbrev, year, abstract) VALUES ('$pmid', '$title', '$authors', '$journalabbrev', '$year', '$abstract')"); 
    echo "This record has been stored into the database!"; 
} 
+0

謝謝。這非常有用! – user1811758 2013-03-23 19:01:43

相關問題