如何返回mysql表中不存在的逗号分隔值?

时间:2013-09-05 18:48:53

标签: php mysql

我正在尝试制作一个接受用户新标签的标签表。

我想排除插入标签表中的常规字词,例如“the”或“that”

我的想法是制作一般词语表,并在插入新标签时将其排除。

这就是我在php上工作的方式:

//get the general words from database and convert them into ary_general

//execlude the general words from the new words and store the rest into ary_tags

//insert the ary_tags words into tags table if doesn't exist.

但如果可以,我希望在一个声明中尽一切努力:

示例:

来源:“做,你,想,那,编程,是,很酷”

tbl_general_words
do
you
that
is

结果: “认为,编程,酷”

2 个答案:

答案 0 :(得分:0)

一种陈述方法可以起作用

<?php
//needs to be configured appropriately
$conn = new PDO($dsn, $user, $password);
// fetch associative arrays, I normally use objects myself though
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// split the string in question into words
$wordsToTag = explode(" ", $phraseToTag);
// create a holder for the common words
$commonWords = array();
// prepare and execute the statement
$stmt = $conn->prepare("SELECT word FROM tbl_general_words");
$stmt->execute();
// add the words to the array
while($row = $stmt->fetch())
{
    $commonWords[] = $row['word'];
}
// get the words that are not common
$wordsToTag = array_diff($commonWords, $wordsToTag);
// build your SQL string
$sql = "INSERT INTO tags (tag) VALUES ";
// fore each word, we'll need a ? to hold the paramater
foreach($wordsToTag as $wordToTag)
{
    $sql .= "(?), ";
}
// remove the trailing space and trailing comma
// this could be achieved with an array and join instead if you prefer
$sql = rtrim(trim($sql), ",");
// add the words
$stmt = $conn->prepare($sql);
$stmt->execute($wordsToTag);
?>

但是,我建议将其作为一种迭代方法,因为它更清晰。

<?php
// the code is the same until the adding part
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$wordsToTag = explode(" ", $phraseToTag);
$commonWords = array();
$stmt = $conn->prepare("SELECT word FROM tbl_general_words");
$stmt->execute();
while($row = $stmt->fetch())
{
    $commonWords[] = $row['word'];
}

$wordsToTag = array_diff($commonWords, $wordsToTag);
// prepare the statement
$stmt = $conn->prepare("INSERT INTO tags SET tag = ?");
foreach($wordsToTag as $wordToTag)
{
    // change the param and execute, because prepared statements are designed for this
    $stmt->bindParam(1, $wordToTag);
    $stmt->execute();
}
?>

答案 1 :(得分:0)

CREATE TEMPORARY TABLE temporary_tags (word VARCHAR(100) NOT NULL);
INSERT INTO temporary_tags VALUES ('do'),('you'),('think'),('that'),('programming'),('is'),('cool');
-- mysql_query("INSERT INTO temporary_tags VALUES ('", implode("'),('", $arr_tags), "');")
INSERT INTO tags (tagColumn, someIntColumn, someStrColumn)
    SELECT temporary_tags.word, 5, 'string value' 
    FROM temporary_tags 
    LEFT JOIN tbl_general_words ON tbl_general_words.word = temporary_tags.word 
    WHERE tbl_general_words.word IS NULL;
DROP TEMPORARY TABLE temporary_tags;