Inserting multiple array values in mySQL database

后端 未结 3 1940
-上瘾入骨i
-上瘾入骨i 2021-01-28 15:43

I have two PHP variables, both strings:

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

$id = \"10288272\";

The structure of the t

相关标签:
3条回答
  • 2021-01-28 16:11
    $comma  = "";
    $values = "";
    $array  = explode(",",$friendslist);
    foreach ($array as $friendid) {
      $values .= $comma."($id,$friendid)";
      $comma = ",";
    }
    $sql = "INSERT INTO UserLinks (User_1, User_2) VALUES $values"
    
    0 讨论(0)
  • 2021-01-28 16:14

    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);
    
    0 讨论(0)
  • 2021-01-28 16:25

    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);
      }
    
    0 讨论(0)
提交回复
热议问题