0

我正在尝试将关联 PHP 数组(一个表)存储到数据库中。这是一个包含许多字段(大约 30 个字段)的大数组,我只想将此数组的 6 个字段存储到一个具有 6 个字段的表中好。该数组的每一行都包含特定文章的信息。我想确保每篇文章只存储一次(不重复),所以在存储数据之前,我需要检查数据库是否有重复查询。这是我的代码无法正常工作。如果有人帮助我,我将不胜感激。

<?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; ?>
4

1 回答 1

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!";
}
于 2013-03-23T00:16:05.223 回答