Inserting multiple array values in mySQL database

后端 未结 3 1945
-上瘾入骨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: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);
    

提交回复
热议问题