从数组插入多个值,并使用PHP和MySQL将它们与单个值相关联

I am parsing a JSON file with PHP and inserting the values into a MySQL database.

I have a table that will associate a person's ID ($constid) with the ID of a meeting they are attending. This is the Attendance table.

The issue I am having is that there are several meeting IDs tied to each person.

The meeting IDs are stored in an array.

Here is the code I am working with to create a table of just the people (constituents):

foreach($json['Constituents'] as $const) {
$dist = $const['District'];
$firstname = $const['FirstName'];
$lastname = $const['LastName'];
$constid = $const['Id'];

$sql = "INSERT INTO Constituents (FirstName, LastName, District, Const_Id)
VALUES ('$firstname', '$lastname', '$dist', '$constid')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully <br />";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

  foreach ($const['MeetingIds'] as $meetids) {
    echo $meetids;
  }

This is the code that inserts into the Attendance table (still within the foreach loop here):

 $sql = "INSERT INTO Attendance (constid, meetid)
VALUES ('$constid', '$meetids')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully <br />";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}

When I insert the meeting IDs, only the first value of each $meetid array is used.

There are 70 people, and 235 meetings, but my table ends up with only 70 rows.

When I experimented with inserting only the meeting IDs, it did grab all 235 Meeting IDs and put them in separate rows.

I would like populate my table with essentially the following:

ConstID | MeetingID
--------------------
12345    | 11111
12345    | 22222
12345    | 33333

How can I accomplish this?

You need to either loop through the $const['MeetingIds'] and run a new insert query for each one, or you need to dynamically build a multi-insert query. This is the easier one, but less performant:

foreach ($const['MeetingIds'] as $meetids) {

    $sql = "INSERT INTO Attendance (constid, meetid) VALUES ('$constid', '$meetids')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully <br />";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

}

The way it is now, your query is outside the loop, so you only get the last value from the foreach iteration.

Alternatively, you can dynamically build a single query within the foreach loop, and then execute it once outside the loop.