简体   繁体   中英

MySQL/PHP update Many-to-Many table

My $_POST array looks like this: ('child_address' in particular)

Array ( 
    [0] => Array ( 
        [child_address] => 123 Street 1 
    ) 
    [1] => Array ( 
        [child_address] => 123 Street 2 
    ) 
)

When I loop over them to insert into MySQL many-to-many table, the last value in my array gets entered for all fields with the same ID in my table.

foreach ($child as $value) {
    $query = "UPDATE M_children
        SET child_address = ?, 
        WHERE personal_id = ?";
    $statement = $db->prepare($query);
    $statement->bind_param('si', $value['child_address'], $_SESSION['mysqlID']);
    $statement->execute();
}

在此处输入图片说明

Several things here:

  1. No need to define the query inside the for loop, it doesn't change.
  2. Not need to prepare the statement inside the for loop, it also doesn't change.
  3. bindParam binds a parameter and when the parameter changes all you need to do is call execute again and it will run the query with the new parameter value.

  4. And this is the bug, You update every row with that person id. If you only want to update one row you need to be more selective with your update query.

When you say "SET child_address = ? WHERE personal_id = ?" and the personal_id of both children is the same(127, in your screenshot), that's going to cause both children to be set to the same address.

You want to either change your query, or change that last param you're passing in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM