PHP将多维数组值插入数据库(如果尚不存在)

时间:2019-08-07 16:13:22

标签: php mysql multidimensional-array

我有一个可以插入数据库的漂亮数组:

$array = array(
    array("USERID", "WORDID", "SUBTITLEID"),
    array("000010001187", "000000008601", "6804500"),
    array("000010001187", "000000008602", "6804500")
);

$fields = implode(', ', array_shift($array));
echo "Fields: <br>";
print_r($fields); //-> USERID, WORDID, SUBTITLEID

$values = array();
foreach ($array as $rowValues) {
    foreach ($rowValues as $key => $rowValue) {
      //escaping
    }
    $values[] = "(" . implode(', ', $rowValues) . ")";
}
echo "<br>Values: <br>";
print_r($values); // -> Array ( [0] => (000010001187, 000000008601, 6804500) [1] => (000010001187, 000000008602, 6804500) )


echo "<br>"."INSERT INTO USERS_WORDS_GER ($fields) VALUES " . implode (", ", $values);

$query = "INSERT INTO USERS_WORDS_GER ($fields) VALUES " . implode (", ", $values);


echo "<br><br>";

try {
  $stmt = $conn->prepare($query);
  $stmt->execute();
  echo '<br>OK';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

输出:

  

字段:USERID,WORDID,SUBTITLEID值:数组([0] =>   (000010001187,000000008601,6804500)[1] =>(000010001187,   000000008602,6804500))插入MYTABLE(USERID,WORDID,   SUBTITLEID)值(000010001187、000000008601、6804500),   (000010001187、000000008602、6804500)

现在,仅当记录中不存在USERID和WORDID时,我才想插入这些行。因此,用户在数据库中只能有一个单词。我试图用“ WHERE NOT EXISTS”来做到这一点,但我不知道如何引用这两列。

0 个答案:

没有答案