插入存储在数组中的所有条目(用于语句)

时间:2016-01-22 07:31:49

标签: php mysql

我将所有密钥存储在数组$ addkeys中(密钥总数总是在变化)。 var_dump($ addkeys)输出:

Arrayarray(9) { [0]=> string(17) "11111-11111-11111" [1]=> string(17) "22222-22222-22222" [2]=> string(17) "33333-33333-33333" [3]=> string(17) "44444-44444-44444" [4]=> string(17) "55555-55555-55555" [5]=> string(17) "66666-66666-66666" [6]=> string(17) "77777-77777-77777" [7]=> string(17) "88888-88888-88888" [8]=> string(17) "99999-99999-99999" }

我想将它们中的每一个插入到数据库中,如果它们不存在的话。我理解如何检查字符串中的单个现有密钥,如果它不存在则执行INSERT,但增量循环会让我感到困惑。任何帮助,将不胜感激。我理解人们可能会建议使用PDO进行mysql查询,但请忽略。

我的代码:

for ($i = 0; $i < count($addkeys); $i++) {

// check each key in $addkeys to see if it exists already in the database to prevent a duplicate entry

$result = mysql_query("SELECT code FROM codes WHERE code = '$addkeys'")
or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_NUM);
$addkeys = $row[0];

if(!isset($addkeys)) {
// entry doesn't exist insert the key
$result = mysql_query("INSERT INTO codes (code, title) VALUES ('$addkeys', 'sample title')")
or die(mysql_error());

}
}

2 个答案:

答案 0 :(得分:1)

您必须使用mysql_num_rows来检查已存储在数据库中的数据。并且您在查询中使用直接数组addkeys,您必须像addkeys[$i]

一样使用它

您的代码将是

for ($i = 0; $i < count($addkeys); $i++) {

// check each key in $addkeys to see if it exists already in the database to prevent a duplicate entry

    $result = mysql_query("SELECT code FROM codes WHERE code = '$addkeys[$i]]'") or die(mysql_error());
    $rows = mysql_num_rows($result);

    if ($rows < 1) {
// entry doesn't exist insert the key
        $insert = mysql_query("INSERT INTO codes (code, title) VALUES ('$addkeys[$i]]', 'sample title')") or die(mysql_error());
    }
}
  

注意: - mysql被删除而不是使用mysqli或PDO

答案 1 :(得分:1)

如果您有键控列,则可以使用on duplicate key update语法

<?php
    foreach( $addkeys as $key ){
        $title='sample title';

        $result = mysql_query("INSERT INTO codes (`code`, `title`) VALUES ('{$key}', '{$title}')
            on duplicate key update `code`={$key}, `title`='{$title}'");    
    }
?>