mysql添加字段里面的数组里面的值,在MySQL数据库中插入多个数组值

I have two PHP variables, both strings:

$friendslist = "2323443,7245,284683,345123,8456234,95432"

$id = "10288272";

The structure of the table I am concerned with is as follows:

Table Name: UserLinks

link_id user_1 user_2

I need to insert these values into the table so that user_1 is always $id, and user_2 is the members of the $friendslist string. It will look like this:

link_id user_1 user_2

1 10288272 2323443

2 10288272 7245

3 10288272 284683

4 10288272 345123

I know the basics of inserting many values, where in this cause I would use:

mysql_query("INSERT INTO UserLinks (User_1, User_2) VALUES ('10288272','2323443'),('10288272','7245'),('10288272','284683')");

But the only way I can think to of to write this (as these values are obviously not the actual values inserted) is something like this:

$friendarray = explode(",", $friendslist);

for ($n = 0; $n < count($friendarray); $n++) {

$friendidpush = "('".$id."','".$friendarray[$n]."'),";

array_push($frienduserarray, $friendidpush);

}

Followed by converting the $frienduserarray to a string, and then including it in my query. This returned an error for me, and I do not think this is the right way to do it... but I am struggling to find a solution online.

解决方案

You aren't initialising $frienduserarray as an array, so array_push doesn't work.

$friendarray = explode(",", $friendslist);

$frienduserarray = array();

for ($n = 0; $n < count($friendarray); $n++) {

$friendidpush = "('".$id."','".$friendarray[$n]."'),";

array_push($frienduserarray, $friendidpush);

}

Note that this seems to be complicating things to me. Why is the second array even necessary? Just use string concatenation.

$query = "INSERT INTO UserLinks (User_1, User_2) VALUES ";

$friendarray = explode(",", $friendslist);

foreach ($friendarray as $friend) {

$query .= "('" . $id . "','" . $friend . "'),";

}

$query = substr($query, 0, -1); // remove trailing comma

mysql_query($query);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值