将逗号分隔的多个字段添加到数据库PHP中


Adding multiple fields separated by comma into database PHP

提前感谢您的帮助!我是PHP的新手,希望能得到一些建议/帮助!我希望使用相同的资源id变量将许多用逗号分隔的id字段分别输入到数据库中。

在此处查找图片链接!在这里,用户为名称输入许多ID,而只为资源输入一个ID,我希望所有ID都输入到数据库中,旁边有相同的资源ID

//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);
} 

我想这可能是上面的代码,但它似乎对我不起作用。。。简言之,我希望用户输入许多ID字段和一个资源字段,并将其单独输入到数据库中。我希望这是有道理的!再次感谢您的帮助!

只回答您的问题而不质疑您的数据库模式。查看以下代码:

$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) . ";";

您可以在一个sql查询中插入多行,方法是用逗号分隔。代码应该生成这样的查询:

INSERT INTO ids_to_resources (id,resource_id) VALUES (1,4),(2,4),(3,4);

您最好创建一个单独的表,为每个记录创建一个新行。。。列将是ID、NINJA_ID、RESOURCE_ID。然后这样插入。对RESOURCE_ID建立索引。这样你就可以很容易地在数据库中搜索特定的记录,更新和删除也会容易得多。

但如果你坚持使用逗号,

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

这行后面没有分号,$id和[$x]之间也没有空格

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