php - LAST_INSERT_ID() 未返回所有标签

标签 php mysql bulkinsert

所以我有如下 3 个表。

TOPICS      TOPIC_TAGS    Tags
topic_id    tag_id        tag_id
topic_data  topic_id      tags

现在我可以成功地将 topic_data 插入到 TOPICS 中,并且标签正在像这样插入......

tag_id    tags
1         this
2         is
3         a
4         test

但是当我尝试将 tag_ids 插入 TOPIC_TAGS 表时,它只是像这样插入最后一个

topic_id  tag_id
0         4

插入主题时也不会插入 topic_id。

这是发布数据的表单。

<form method="post" action="add_topic.php">
<table>
<tr>
<td align="left"><b>Enter your Topic keywords.
    <ul id="topic" name="tags[]"></ul>

</td>
</tr>
<tr>
<td colspan="3"><textarea name="topic_data" cols="50" rows="3" id="topic_data" placeholder="What Topic are you talking about?"></textarea></td>
</tr>
<tr>
<td colspan="3" align="right">Invisipost: <input type="hidden" name="invisipost" value="0"><input type="checkbox" name="invisipost" value="1"> <input type="submit" name="Submit" value="Talk" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</form>

这是我的代码:

$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';
}
$sql_s = "SELECT * from tags where tag_id='$tags'";
$tag_id = isset($_GET['tag_id']) ? $_GET['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);

最佳答案

不再支持mysql_*函数,它们是officially deprecated不再维护并将 removed将来。您应该使用 PDO 更新您的代码或MySQLi确保您的项目将来的功能。

由于您使用的是 mysql_*,因此您应该使用 mysql_real_escape_string以防止注入(inject)。

<小时/>

注意:我的示例仅涵盖您在问题顶部提供的表格信息,您必须自己添加任何其他列。

使用 MySQLi 和准备好的语句,您可以轻松防止使用准备好的语句进行注入(inject)。

bind_param 负责处理您要插入的数据类型,例如 i 代表整数,s 代表字符串,因此对于每个? 您在查询中将其及其各自的类型添加到 bind_param 中。 <强> Read more about bind_param here.

我的测试表:

<form method="post" action="add_topic.php">
<table>
<tr>
<td align="left"><b>Enter your Topic keywords.<br />
<input id="topic" name="tags">
</td>
</tr>
<tr>
<td colspan="3"><textarea name="topic_data" cols="50" rows="3" id="topic_data" placeholder="What Topic are you talking about?"></textarea></td>
</tr>
<tr>
<td colspan="3" align="right">Invisipost: <input type="hidden" name="invisipost" value="0"><input type="checkbox" name="invisipost" value="1"> <input type="submit" name="Submit" value="Talk" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</form>

数据库.php:

<?php
// fill with your data
$db_host = 'localhost';
$db_user = 'stackoverflow';
$db_pass = 'stackoverflow';
$db_name = 'stackoverflow';

$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

add_topic.php:

<?php
include_once "database.php";
$tags = $_POST['tags'];
$topic_data = $_POST['topic_data'];
$ids = array();

if (!isset($topic_data))
{
    die("<h2>Opps...</h2><p>You did not fill out the topic data field.</p>");
}

if (!isset($tags))
{
    die("<h2>Opps...</h2><p>You did not fill out the tags field.</p>");
}

foreach (explode(' ', $tags) as $tag)
{
    if ($stmt = $con->prepare("SELECT tag_id FROM tags WHERE tags=?"))
    {
        $stmt->bind_param("s", $tag);
        $stmt->execute();
        $stmt->bind_result($id);
        $stmt->fetch();
        $stmt->close();
    }

    if ($id == 0)
    {
        if ($stmt = $con->prepare("INSERT INTO tags (tags) VALUES(?)"))
        {
            $stmt->bind_param("s", $tag);
            $stmt->execute();
            $stmt->bind_result($id);
            $stmt->fetch();
            $ids[] = $stmt->insert_id;
            $stmt->close();
        }
    }
    else
        $ids[] = $id;
}

if ($stmt = $con->prepare("INSERT INTO topics(topic_data) VALUES(?)"))
{
    $stmt->bind_param("s", $topic_data);
    if ($stmt->execute())
    {
        $topic_id = $stmt->insert_id;
        $stmt->close();
        foreach ($ids as $id)
        {
            if ($stmt = $con->prepare("INSERT INTO topic_tags (topic_id, tag_id) VALUES(?, ?)"))
            {
                $stmt->bind_param("ii", $topic_id, $id);
                $stmt->execute();
                $stmt->close();
            }
        }     
    }
    else
        $stmt->close();
}

echo "<h2>Topic successfully inserted</h2><p>The topic and tags have been inserted.</p>";
$con->close();

正如你在我的代码中看到的,当我检查标签时,我还会检索已经存在的标签的 id 并将它们全部存储到数组 $ids 中以供以后重用对于表 topic_tags

成功插入主题后,我检索主题 ID,然后将所有标签 ID 与主题 ID 一起插入到 topic_tags 表中。

在我的测试表单上,我使用了简单的标签输入,但是如果您将其用作数组,您也可以更改它:

if (!isset($tags))

致:

if (!isset($tags) || !is_array($tags))

并更改:

foreach (explode(' ', $tags) as $tag)

致:

foreach ($tags as $tag)

关于php - LAST_INSERT_ID() 未返回所有标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779044/

相关文章:

sql-server - 在部署后脚本中批量插入

c# - SqlBulkCopy.BulkCopyTimeout 属性

php - Laravel 自定义验证——获取参数

php - <a href ="path to dir"> 不会作为 PHP echo 下载

mysql - 如何在单个字段或列中连接多个值? (MySQL)

mysql - 如果在连接中完成过滤或在连接后使用 where 子句,哪个查询更快

php - 在 PHP 中过滤类别(两个或多个)之间的共同值

mysql - 在mysql中批量插入和更新

php - Carbon 现在存储在变量 laravel 中后日期错误

javascript - 如何使用 PHP 处理 Controller 的 XMLhttp 请求