在MySQL数据库中插入多个数组值 [英] Inserting multiple array values in mySQL database

查看:496
本文介绍了在MySQL数据库中插入多个数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个PHP变量,都是字符串:

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:

表名称:UserLinks

Table Name: UserLinks

link_id   user_1    user_2

我需要将这些值插入表中,以便user_1始终是$ id,而user_2是$ friendslist字符串的成员.看起来像这样:

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

接着将$ frienduserarray转换为字符串,然后将其包括在我的查询中.这为我返回了一个错误,我认为这不是正确的方法……但是我正在努力寻找在线解决方案.

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.

推荐答案

您没有将$frienduserarray初始化为数组,因此array_push不起作用.

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

这篇关于在MySQL数据库中插入多个数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆