用多个数据更新MySQL

时间:2018-07-03 10:16:21

标签: php mysql

我想用多选更新表。多选具有MySQL数据。如果一个员工有1家公司,但它有2家或更多,则它没有更新。

enter image description here

我在选择菜单中显示当前公司。因此,Employee#1有2个公司,但是如果我选择另一个2,它并没有更新。我该如何解决? employee_company是我的相关表。

多选

<select size="10" name="company[]" id="company" class="form-control" multiple>
   <?php 
      $query2 = "SELECT * FROM company GROUP BY company_id";  
      $result2 = mysqli_query($connect, $query2);  
      while($row2 = mysqli_fetch_array($result2)){
   ?>
   <option value="<?php echo $row2['company_id'];?>"><?php echo $row2['name'];?></option>
   <?php }?>
</select>

更新

$name = mysqli_real_escape_string($connect, $_POST["name"]);  
$address = mysqli_real_escape_string($connect, $_POST["address"]); 
$company = mysqli_real_escape_string($connect, $_POST["company"]);

$id = $_POST["employee_id"];

if($id != ''){             
    foreach($_POST['company'] as $comp){
        $query = "
        UPDATE      employee t1
        LEFT JOIN   employee_company t2 ON (t1.employee_id = t2.employee_id)            
        SET         t1.name='$name',
                    t1.address='$address',
                    t2.employee_id='$id',
                    t2.company_id='$comp'            
        WHERE       t1.employee_id='$id'"; 
    }               
       $message = 'Data Updated';            
  }  
  else{  
  }  
  if(mysqli_query($connect, $query)){  
       $output .= '<label class="text-success">' . $message . '</label>';  
  }  
  echo $output;

1 个答案:

答案 0 :(得分:3)

company[]是一个数组-如果要将值作为字符串,则必须IMPLODE值。

 $company = mysqli_real_escape_string($connect, implode(",",$_POST["company"]));

我的建议是修改数据模型并对其进行规范化-不要将公司ID作为字符串放在列company_id中,而应使用表employee_companies来保存员工与零/之间的关联一个/很多公司。

更新

我的意思是这样的

"START TRANSACTION"
"UPDATE employee SET name = '$name', address = '$address' WHERE employee_id = $id"
"DELETE FROM employee_company WHERE employee_id = $id"

if(is_array($_POST["company"])) 
{
  $values = Array();
  foreach($_POST["company"] as $c_id) $values[] = "($id, $c_id)";

  "INSERT INTO employee_company(employee_id, company_id) VALUES ".implode(",", $values)
}
"COMMIT"