繁体   English   中英

将关联的PHP数组存储到数据库中,无需重复

[英]Store an associative PHP array into the database without duplication

我正在尝试将一个关联的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; ?>

这是一些未经测试的代码,可以更快地执行此操作:

$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!";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM