在PHP中将多维数组插入mysql表的最佳方法是什么

时间:2018-07-04 08:49:48

标签: php mysql arrays

我的问题与this question非常相似。但是,与this question中的数组不同,我的数组没有字段名值。我的数组如下所示:

      Array
    (
        [0] => Array
            (
                [0] => Extraction and characterisation of gelatin from the skin of striped catfish (Pangasianodon hypophthalmus) and studies on its colour improvement
                [1] => EMAIL FREE FULL TEXT                          DOWNLOAD FULL TEXT
                [2] => Prabjeet Singh,            Soottawat Benjakul
                [3] => 1-9
                [4] => http://dx.doi.org/10.5897/AJB2013.13121
            )

        [1] => Array
            (
                [0] => Electrolyte ions and glutathione enzymes as stress markers in Argania spinosa subjected to drought stress and recovery
                [1] => EMAIL FREE FULL TEXT                          DOWNLOAD FULL TEXT
                [2] => Abdelghani Chakhchar,            Mouna Lamaoui,            Salama Aissam,            Abderrahim Ferradous,            Said Wahbi,            Abdelhamid EI Mousadik,            Saad Ibnsouda-Koraichi,            Abdelkarim Filali-Maltouf,            Cherkaoui El Modafar
                [3] => 10-21
                [4] => http://dx.doi.org/10.5897/AJB2016.15234
            )

        [2] => Array
            (
                [0] => Molecular detection of disease resistance genes to powdery mildew (Blumeria graminis f. sp. tritici) in wheat (Triticum aestivum) cultivars
                [1] => EMAIL FREE FULL TEXT                          DOWNLOAD FULL TEXT
                [2] => Vincent Mgoli Mwale,            Xiuli Tang,            Eric Chilembwe
                [3] => 22-31
                [4] => http://dx.doi.org/10.5897/AJB2016.15720
            )
)

我正在尝试将此数组数据放入mysql表中。我正在使用的php代码如下所示(见下文):

foreach ($newref as $key=>$values){
    $title = $values[0];
    $authors = $values[2];
    $pages = $values[3];
    $doi = $values[4];
    $query = "INSERT INTO citations (id,title,authors,pages,doi) VALUES (:title,:authors,:pages,:doi)";
        $sql=$con->prepare($query);
        $sql->execute(array(
            ':title' => $title,
            ':authors' => $authors,
            ':pages' => $pages,
            ':doi' => $doi

        ));
}

以某种方式我无法将数据插入表中。我的Db连接正常,没有报告任何错误。我可能做错了什么?将此类数据插入mysql表的最佳/简便方法是什么? 我不知所措...预先感谢您

1 个答案:

答案 0 :(得分:1)

如果表中的id属性是自动递增的,则应将其从查询中删除。它会自动获取下一个递增的值,并仅插入其他列/字段。

查询应类似于:

$query = "INSERT INTO citations (title,authors,pages,doi) VALUES (:title,:authors,:pages,:doi)";

顺便说一下,您正在朝正确的方向尝试。