【问题标题】:Store an associative PHP array into the database without duplication将关联的 PHP 数组存储到数据库中而不重复
【发布时间】:2013-03-22 23:32:30
【问题描述】:

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

【问题讨论】:

  • 你的阵列是什么样子的?请编辑您的问题并添加数组

标签: php mysql database associative-array


【解决方案1】:

这里有一些未经测试的代码可以更快地完成:

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

【讨论】:

  • 谢谢。很有用!
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 2013-12-15
  • 2014-01-28
  • 2014-01-11
  • 2016-08-14
  • 1970-01-01
  • 2015-06-08
  • 2019-05-04
相关资源
最近更新 更多