foreach循环有2个mysql查询

时间:2013-04-17 17:45:49

标签: php mysql foreach

我签约了一个简单的标记系统,

我的PHP页面获取一串标签, 首先它'exlpode'他们然后我使用foreach循环在id-tagname表中找到标签id, 一旦我找到了标签id,我将它放在另一个名为articledtaged的表中,其中有两个值,文章ID和标签ID。

这是代码:

if (isset($_POST['tag'])&&!empty($_POST['tag'])){
    $tag = $_POST['tag'];
    $tagsarr = explode(",", $tag);
    print_r ($tagsarr);
    foreach($tagsarr as $key=>$row){
    echo $row ;

    $tagidquery = "SELECT id FROM tags WHERE tagname = '$row'";
    $results = mysql_query($tagidquery);
    $tagidarr = mysql_fetch_assoc($results);
    $tagid = $tagidarr['id'];
    echo $tagid;

    $taginsertquery = "INSERT INTO tagedarticle (articleid,tagid) VALUES('$yourarticleid','$tagid')";
    mysql_query($taginsertquery);
    }

但第二部分只运作一次,

例如,如果我有3个标签,“酷”,“精彩”,“跛脚”,每个都有自己的id(对于这个例子,可以说4-6)。 结果将是

tagname     tagid    
cool         4
wonderful  (empty)
lame       (empty)

但为什么?!

请告知。

3 个答案:

答案 0 :(得分:1)

如果你稍微改变了逻辑怎么办?您正在用逗号爆炸标记值,所以为什么不使用IN语句将其放入select查询中。然后你可以遍历返回的Tag Ids并将它们插入到你的多对多表中。

if ( isset($_POST['tag']) && !empty($_POST['tag']) ) {
    $tag = "'" . str_replace(",", "','", $_POST['tag']) . "'";
    $tagidquery = "SELECT id FROM tags WHERE tagname IN ($tag)";
    $results = mysql_query($tagidquery);
    while($row = mysql_fetch_assoc($results))
    {
        $tagId = $row['id'];
        $taginsertquery = "INSERT INTO tagedarticle (articleid,tagid) VALUES('$yourarticleid','$tagId')";
        mysql_query($taginsertquery);
    }
}

答案 1 :(得分:0)

清洁:


if (empty($_POST['tag']))
    return;

$tagsarr = explode(",", $_POST['tag']);
$tagsSQL = array();
foreach ($tagsarr as $tag)
    $tagsSQL[] = '"'.mysqli_real_escape_string($link, trim($tag)).'"';

$tagidquery = "SELECT id FROM tags WHERE tagname IN (".implode(",", $tagsSQL.")";
$results = mysql_query($tagidquery);
while($row = mysql_fetch_assoc($results)) {
    $tagId = $row['id'];
    $taginsertquery = "INSERT INTO tagedarticle (articleid,tagid) VALUES(".intval($yourarticleid).",".intVal($tagId).")";
    mysql_query($taginsertquery);
}

答案 2 :(得分:0)

你可以使用mysqli预处理语句在循环中更好地工作并防止sql注入:

if ( isset($_POST['tag']) && !empty($_POST['tag']) )
{
    $tag     = $_POST['tag'];
    $tagsarr = explode(",", $tag);
    $con     = new mysqli('host', 'username', 'password', 'database');
    $select  = $con->prepare("SELECT id FROM tags WHERE tagname=? LIMIT 1");
    $insert  = $con->prepare("INSERT INTO tagedarticle (articleid,tagid) VALUES(?,?)";
    foreach($tagsarr as $key=>$row)
    {
        $select->bind_param("s", $row);
        $select->execute();
        $select->bind_result($id);
        $select->fetch();

        $insert->bind_param('ss', $yourarticleid, $id);
        $insert->execute();
    }
    $select->close();
    $insert->close();
    $con->close();
}