2016-03-29 7 views
-1

あらかじめご協力いただきありがとうございます!私はPHPにはとても新しく、助言や助けが大好きです!私はカンマで区切られた多くのidフィールドを、同じresource id変数を持つデータベースに別々に入力したい。複数のフィールドをカンマで区切ってデータベースに追加するPHP

Find a link to a picture here! Here, a user enters many ids for the name, and only one ID for the resource, I would like all ids to be entered into the database with the same resource id beside it

//so this is creating the array to split up the ids 
$array = explode(",", $id); 
//finding length of array 
$length = count($array); 
//now we want to loop through this array, and pass in each variable to the db 
for ($x = 0; $x < $length; $x++) { 
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id) 
    VALUES ($id [$x], $resource_id)" 

    $result = mysqli_query($dbcon,$sqlinsert); 
} 

が、私はそれが上記のコードのようなものかもしれないと思いますが、それは私のために働いているように見えるdoes notの...要するに は、私は、ユーザーが多くのIDフィールドと一つだけのリソースを入力しますこれをデータベースに別々に入力する必要があります。私はこれが理にかなってほしい! 何か助けてくれてありがとう!

$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id) 
VALUES ($id[$x], $resource_id)"; 

答えて

0

あなたは、新しい行を持つ別のテーブルを作成したほうが良いでしょうレコードごとに...列はID、NINJA_ID、RESOURCE_IDになります。そのように挿入します。 RESOURCE_IDに索引を付けます。この方法で、特定のレコードのデータベースを簡単に検索することができます。更新と削除はさらに簡単になります。

しかし、あなたがやってコンマを主張する場合、

$comma_ids = implode("," $array);

0

あなたは、この行の後にセミコロンを持っていない、あなたは$ IDと[$ xに]の間にスペースを持っているmusnt't

1

にのみ、あなたの質問に答えると、あなたのデータベーススキーマを問うていません。次のコードを見てください:

$ids = explode(",", $id); 
$inserts = array(); 
foreach ($ids as $id) { 
    $inserts[] = "($id,$resource_id)"; 
} 
$query = "INSERT INTO ids_to_resources (id,resource_id) VALUES " . implode(',', $inserts) . ";"; 

複数の行をカンマで区切って1つのSQLクエリに挿入できます。コードは次のようなクエリを生成します:

INSERT INTO ids_to_resources (id,resource_id) VALUES (1,4),(2,4),(3,4); 
関連する問題