Inserting multiple array values in mySQL database

2020-05-05 17:40发布

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.

标签: php mysql insert
3条回答
Lonely孤独者°
2楼-- · 2020-05-05 18:29
$comma  = "";
$values = "";
$array  = explode(",",$friendslist);
foreach ($array as $friendid) {
  $values .= $comma."($id,$friendid)";
  $comma = ",";
}
$sql = "INSERT INTO UserLinks (User_1, User_2) VALUES $values"
查看更多
走好不送
3楼-- · 2020-05-05 18:30

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);
查看更多
叛逆
4楼-- · 2020-05-05 18:31

You are getting this error because you have not declared the $frienduserarray as array any where in your code. Just declare it

 $frienduserarray=array();

before the for loop. After that your code should look like

  $friendarray = explode(",", $friendslist);
  $frienduserarray=array();
  for ($n = 0; $n < count($friendarray); $n++) {
      $friendidpush = "('".$id."','".$friendarray[$n]."'),";
      array_push($frienduserarray, $friendidpush);
  }
查看更多
登录 后发表回答