【发布时间】:2014-11-02 10:20:38
【问题描述】:
我通过 mysql 查询返回了以下结果:
tag_id article_id (asc) name tag_slug
56 69487 Exploration exploration
10 69488 Events events
32 69488 Military military
28 69489 Arts arts
3 69489 Religion churches
36 69490 Forestry forestry
8 69490 Industry industry
40 69490 Man-Made man-made
42 69490 Politics politics
我需要遍历结果并创建一个字符串,其中包含与每组文章 ID 相关联的 tag_slugs。这部分代码不需要 name 和 tag_id 列。
例如...
69487 会有一个字符串:'
69488 将有一个字符串:'
69489 会有一个字符串:'
69490 将有一个字符串:'
...一个名为 tags 的列将在数据库中使用这些字符串和相应的 article_id 进行更新。
我在下面的尝试有点工作,但总是忽略最后一次数据库更新。我确信必须有更好更合乎逻辑的方法,但现在我做不到。
$previous_article_id = 0;
while( $row = $result->fetch_assoc() )
{
if ( $row['article_id '] != $previous_article_id && $previous_article_id != 0 )
{
$sql = "
UPDATE
".ARTICLE_TABLE."
SET
tags = '".$tags."'
WHERE
id = ".$previous_article_id."
";
$db->query($sql) OR sql_error($db->error.$sql);
$tags = '';
}
if ( $row['article_id '] == $previous_article_id || $previous_article_id == 0 )
{
$tags .= '<'.$row['tag_slug'].'>';
}
$previous_article_id = $row['article_id '];
}
是的,我知道它应该是 PDO,而且代码有点疯狂,但我在朋友兄弟网站上工作,所以没有太多权限来更改它。
【问题讨论】:
-
你的意思是
tags是一个单独的字段,它的值应该是<forestry><industry><man-made><politics>说article_id69490? -
您确定您的代码正在打印 id 69488 的
和 标签吗?因为它看起来不是,或者我错过了一些东西。 -
@Jenson M John 是的,tags 是同一张表中的另一列
-
@Malcolm Kindermans 你是对的,只打印了事件标签。应该是事件和军事。代码未按预期运行。
标签: php mysql optimization logic