php - 在 1 个查询中将数据插入到 3 个表中

标签 php mysql select insert

基本上我有一个带有与该网站类似的 tag-it 系统的网站,我的表结构如下

TOPICS      TOPIC_TAGS    TAGS
topic_id    tag_id        tag_id
topic_data  topic_id      tags

现在我想做的是运行一系列查询,以便在发布主题时,将相关主题数据输入到主题表中(当前正在工作),将标签放入标签表中(当前正在工作) ,然后将 TAGS 表中的 tag_id 放入 TOPIC_TAGS 表中具有链接 topic_ids 的行中(当前不工作)

现在它并没有像标签表那样将tag_ids输入topic_tags,它只是将LAST标签信息输入到行中并且不存储关联的topic_ids

这是我的代码

$tags = isset($_POST['tags']) ? $_POST['tags'] : null;

if (is_array($tags)) {
foreach ($tags as $t) {
    // Checking duplicate
     $sql_d = "SELECT * from tags where tags='$t'"; 
      $res=mysql_query($sql_d);
      $res = mysql_num_rows($res);
    if($res<1)
    {
    // escape the $t before inserting in DB
    $sql = "INSERT INTO tags (tags) VALUES('$t')";
    mysql_query($sql);
    }
 }
} else {
echo 'Invalid tag';
}

$tag_id = isset($_POST['tag_id']) ? $_POST['tag_id'] : null;

if (is_array($tag_id)) {
foreach ($tag_id as $tid) {

    // escape the $t before inserting in DB
    $sql = "INSERT INTO topic_tags (tag_id) VALUES('$tid')";
    mysql_query($sql);
    }
 }

$sql="INSERT INTO topic_tags (tag_id)VALUES(LAST_INSERT_ID())";
$result=mysql_query($sql);


$topic_data= htmlentities($_POST['topic_data']);
$posted_by = $_SESSION['user_id'];
$posted = "date_add(now(),INTERVAL 2 HOUR)";
$invisipost = isset($_POST['invisipost']) ? $_POST['invisipost'] : 0 ;

if (($topic_data=="")) 
echo "<h2>Opps...</h2><p>You did not fill out all the required fields.</p>";

else 
$sql="INSERT INTO topics(topic_data, posted_by, posted, invisipost)VALUES('$topic_data', '$posted_by', $posted, $invisipost)";
$result=mysql_query($sql);

if($result){

$sql="INSERT INTO topic_tags (topic_id)VALUES(LAST_INSERT_ID()) WHERE topic_tags.tag_id='". $_GET['tags'] ."'";
$result=mysql_query($sql);

编辑

我最好先添加主题数据,然后添加标签,然后添加 topic_tags 信息吗?

最佳答案

我认为你应该在“foreach”循环的一步中插入topic_tags。最后查询

$sql="INSERT INTO topic_tags (topic_id)VALUES(LAST_INSERT_ID()) WHERE topic_tags.tag_id='". $_GET['tags'] ."'"

既不是插入也不是更新,肯定是错误的

(编辑) 所以很可能您需要以下内容:

foreach ($tag_id as $tid) {

    // escape the $t before inserting in DB
    $sql = "INSERT INTO topic_tags (topic_id,tag_id) VALUES($topic_id,$tid)";
    mysql_query($sql);
}

关于php - 在 1 个查询中将数据插入到 3 个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17773812/

相关文章:

PHP MySQL 更新查询

php - 尝试在 PHP 中创建匹配模式内模式的正则表达式

mysql - SQL 查询没有结果集

mysql - 如何选择某些 'id'的和并将结果按组划分

php - 为什么我在使用命名参数时会看到 "invalid parameter number"错误?

php - 在 php 中获取当前一周中的第一天和最后一天

php - EC2 Ubuntu mysql_connect 函数导致 500 Internal Server Error

Python 和 Pandas 查询 API 和更新数据库

javascript - 通过下拉选择更改div中特定图像的图像源

mysql - 从没有自动 ID 的表中选择最后 250 行