LAST_INSERT_ID()没有为所有标签返回

时间:2013-07-22 02:22:57

标签: php mysql bulkinsert

所以我有3张表如下。

TOPICS      TOPIC_TAGS    Tags
topic_id    tag_id        tag_id
topic_data  topic_id      tags

现在我可以成功地将topic_data插入到TOPICS中,并且正在插入TAGS ......

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);

1 个答案:

答案 0 :(得分:0)

mysql_* 功能不再支持,它们为officially deprecated不再维护将来removed。您应该使用PDOMySQLi更新代码,以确保将来的项目功能。

由于您使用的是 mysql_* ,因此您应该使用mysql_real_escape_string来阻止注射。


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

使用MySQLi和预处理语句,您可以轻松地使用预准备语句来防止注入。

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>

database.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中,以便稍后重用于表{ {1}}。

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

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

topic_tags

要:

if (!isset($tags))

并改变:

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

要:

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