将多个项插入数据库行并返回以逗号分隔的结果

时间:2016-03-26 16:53:46

标签: php mysql database

有没有办法将多个项目插入数据库行,然后将结果及其对应部分作为逗号返回?

例如:

POST
POSTID       URL                                              HITS
1            http://google.com,http://facebook.com            35,20

所以说帖子1中有2个网址,谷歌有35个点击,而facebook有20个。现在我想用以下内容显示结果:

$query = $db->query_first("
  SELECT * FROM ". TABLE_PREFIX ."post
  WHERE url = '" . $drc_url . "'
");

但我只想一次拉一个URL及其相应的匹配值。这可能吗?如果是这样,有人能指出我正确的方向吗?

现在我的php看起来像:

$query = $db->query_first("SELECT * FROM ". TABLE_PREFIX ."post WHERE url = '" . $drc_url . "'"); 
      if (!$query){ 
          $db->query_write("INSERT INTO ". TABLE_PREFIX ."redirect (url, hits) VALUES ('" . $drc_url . "', 1)");
      } else { 
          $db->query_write("UPDATE ". TABLE_PREFIX ."redirect SET hits = hits + 1 WHERE url = '" . $drc_url . "'"); 
      }  

但如果它们位于相同的$ postid中,我希望它们全部放在同一行

1 个答案:

答案 0 :(得分:0)

请参阅代码中的注释。

$drc_url = "http://google.com";

/* insert/update */
$query = $db->query("SELECT * FROM ". TABLE_PREFIX ."post WHERE url LIKE '%" . $drc_url . "%'");
if ( $query->num_rows > 0 ) {
    // the URL can be in multiple rows - go through each row
    while( $row = $query->fetch_assoc() ) {
        //find the URL position/index within the list
        //if it's possible that the URLs are already separated by anything else than comma (for example "comma and space", "space", etc), you need to add functionality to be able to find them correctly
        $urls = explode( ',', $row[ 'url' ] );
        $index = array_search( $drc_url, $urls );
        //same as previous comment goes for the hits row
        $hits = explode( ',', $row[ 'hits' ] );
        //increment the hits number on the correct value
        $hits[$index]++;
        //update the hits (put them back as a string from the array with already incremented value) - use unique identificator in the WHERE clause
        $db->query("UPDATE ". TABLE_PREFIX ."redirect SET hits = '" . implode( ',', $hits ) . "' WHERE postid = '" . $row[ 'postid' ] . "'");
    }
} else {
    // the URL was not found - insert
    $db->query("INSERT INTO ". TABLE_PREFIX ."redirect (url, hits) VALUES ('" . $drc_url . "', 1)");
}


/* select */
//same functionality as above, just not updating
$query = $db->query("SELECT * FROM ". TABLE_PREFIX ."post WHERE url LIKE '%" . $drc_url . "%'");
while( $row = $query->fetch_assoc() ) {
    $urls = explode( ',', $row[ 'url' ] );
    $index = array_search( $drc_url, $urls );
    $hits = explode( ',', $row[ 'hits' ] );
    echo "URL " . $drc_url . " has " . $hits[$index] . "hits";
}

但正如Mark Ba​​ker在评论中写道的那样,更改数据库结构然后构建新结构会好得多。