如何从数据库中获取标签?

时间:2015-03-07 12:09:22

标签: php tags

我的数据库结构:

News:

id | title |description | slug

Tags:

id | title | slug

Tags news:

id | id tags | id news

代码:

$sqltagi = mysql_query("SELECT id_tags FROM tags_news WHERE id_news LIKE '%$id%' ORDER BY id_tagu DESC");

if (!$sqltagi)
{
    echo 'Error: ' . mysql_error();
    exit;
}

$row = mysql_fetch_array($sqltagi);

$lol=$row['id_tagu'];

$sql = mysql_query("SELECT title,slug FROM tags WHERE id LIKE '%$lol%'");
//$sqlq = mysql_fetch_array($sql);


while ($rowid = mysql_fetch_array($sql)) 
{
    $aa1=$rowid['title'];
    $aa2=$rowid['slug']; 

    $tags=''.$aa1.' '.$aa2.'';
}

怎么样?

2 个答案:

答案 0 :(得分:0)

请试试这个......

$sqltagi = mysql_query("SELECT id_tags FROM tags_news WHERE id_news LIKE '%$id%' ORDER BY id_tagu DESC");

if (!$sqltagi)
{
    echo 'Error: ' . mysql_error();
    exit;
}

while($row = mysql_fetch_array($sqltagi))
{

$lol=$row['id_tags'];

$sql = mysql_query("SELECT title,slug FROM tags WHERE id LIKE '%$lol%'");
//$sqlq = mysql_fetch_array($sql);


    while ($rowid = mysql_fetch_array($sql)) 
    {
        $aa1=$rowid['title'];
        $aa2=$rowid['slug']; 

        $tags=''.$aa1.' '.$aa2.'';
    }
}

答案 1 :(得分:0)

好几件事!首先,请不要使用mysql函数!
它们不安全,容易发生sql注入 使用mysqlipdo,您应该研究joins in sql

但是如果你必须使用mysql函数,那么你可以这样做:

<?php

    $sql = mysql_query("SELECT title, slug FROM tags JOIN tags_news ON tags.id = tags_news.id_tags");

    while ($rowid = mysql_fetch_array($sql)) {
        $aa1 = $rowid['title'];
        $aa2 = $rowid['slug']; 

        echo $tags = '' . $aa1 . ' ' . $aa2 . '<br />';
    }

?>