2016-03-26 9 views
0

複数の項目をデータベース行に挿入し、結果とその部分をコンマで戻す方法はありますか?データベース行に複数の項目を挿入し、結果をカンマで区切って返します

例えば

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

Facebookは今、私のようなものを使用してその結果を表示する20を有しているので、ポスト1は、その中に2つのURLを持っていると言う、Googleは、35件のヒットがあります

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

しかし、私は、一度に1つの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で聞きしたい場合は、コード内のコメントを参照してください同じ行

+0

はい、データテーブルを正常に正規化するとはるかに簡単です –

+0

上記のように、正規化を参照してください – Strawberry

答えて

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"; 
} 

しかし、マーク・ベイカーがコメントで書いたように、DBの構造を変更し、新構造の上に構築するために非常に良いだろう。

関連する問題