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

标签 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

结果: “思考、编程、酷”

最佳答案

单一语句方法可行

<?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();
}
?>

关于php - 如何返回mysql表中不存在的逗号分隔值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18643765/

相关文章:

PHP - 浏览器中的 shell_exec 输出为空

php - Javascript 和 Php (MVC)

php - 在 MySQL 和 HTML 中使用相同的列名

php - 有人能解释一下为什么我的 MySQL 表数据没有显示吗?

php - 什么时候使用 utf8_encode 和 utf8_decode 是正确的时间?

MySQL备份命令不起作用

mysql - 提高 MySQL 查询性能 - 数学密集型查询

java - 无法初始化类 com.mysql.jdbc.StringUtils

mysql - 如何安全地加密数据库中的信用卡信息

mysql - 从 mysql 中提取数据并在查询中进行计数/分组