This paper illustrates two ways to update the data of the intermediate relational table by the example form of PHP. Share for everyone to use for reference. The specific methods are as follows:
First, the intermediate correlation table: the middle table here only saves the primary key of table 1 and the primary key of table 2, that is, Many-to-many form.
Perform data additions and deletions as frame internal methods, not part of the idea.
Method One: Delete the old data first, then add the new data
$res = $this->classes->classedit ($id, $data); Modify the primary table data
if ($res)
{
//delete association table data First
$bool = $this->lesson_classes->lessonclassesdel ($id);
if ($bool)
{
//cyclic assembly condition, add Data
foreach ($lesson _ids as $val)
{
$arr = array (' class_id ' => $id, ' lesson_id ' => $val); Data
$res = $this->lesson_classes->lessonclassesadd ($arr); Perform add
}
}
$this->show_tips (' Operation successful! ');
}
else
{
$this->show_tips (' Operation failed! ');
}
Use this method disadvantage: Mass Delete data This is not safe, there is a certain degree of security risks.
Method Two: Only add the need, only delete the
Old data identified in the library: $arr _old (processed one-dimensional array)
//Submitted new data: $arr _new (resulting one-dimensional array)
$intersect = Array_intersect ($arr _old, $arr _ New); Intersection (the part that needs to be retained without processing)
$result _del = Array_diff ($arr _old, $intersect);
$result _add = Array_diff ($arr _new, $intersect) that need to be removed from the old data; Added
//Add additional data to new data
if ($result _add && is_array ($result _add))
{
foreach ($result _add as $ val)
{
$data _add = Array (' class_id ' => $id, ' lesson_id ' => $val); Data
$bool _add = $this->lesson_classes->lessonclassesadd ($data _add); Perform add
}
//Remove data that needs to be purged
if ($result _del && is_array ($result _del))
{
foreach ( $result _del as $val)
{
$bool _del = $this->lesson_classes->lessonclassesdel ($id, $val);//Perform Delete
}
}
if ($bool _add && $bool _del)
{
$this->show_tips (' successful operation! ');
}
else
{
$this->show_tips (' Operation failed! ');
}
The method features: targeted to add data and delete data, compared to the first method, high security
I hope this article will help you with your PHP program design.