PHP循环插入和更新

时间:2019-10-24 06:59:30

标签: php loops for-loop

我这里有这个php脚本,我想基于$id$name更新表。参照脚本,表已成功更新id='1' with name='A'id='2' with name='B'。但是名称C,D尚不包含ID值。显然,我需要执行插入查询。但是,如何基于尚无ID的剩余名称循环插入查询?

如果尺寸为id > name,我还需要删除没有id的其余name。感谢您的帮助。

<?php
  $id   = "1,2";
  $name = "A,B,C,D";

  $sliptId = explode(",", $id);
  $sliptName = explode(",", $name);

  $sizeOfId = sizeof($sliptId);
  $sizeOfName = sizeof($sliptName );

  if(($sizeOfId < $sizeOfName ) || ($sizeOfId > $sizeOfName)){
    //not even data
    for($x=0; $x< $sizeOfId; $x++ ){
      $sql = "UPDATE tbl
              SET name = '".$sliptName[$x]."' 
              WHERE id = '".$sliptId[$x]."' ";  
      echo $sql;

    }
  }else{
    //even data. Update as normal.
  }
?>

2 个答案:

答案 0 :(得分:0)

可以完成以下操作:

$result = array_map(null, $sliptId, $sliptName);
print_r($result);
// you can see that now you have array of pairs from each `$slipt*` array 
// and where values from first array don't exist - first key is `empty`

foreach ($result as $pair) {
    if (empty($pair[0])) {
        // do Insert
    } else {
        // do Update
    }
} 

答案 1 :(得分:0)

<?php
  $id   = "1,2";
  $name = "A,B,C,D";

  $sliptId = explode(",", $id);
  $sliptName = explode(",", $name);

  $sizeOfId = sizeof($sliptId);
  $sizeOfName = sizeof($sliptName );

  if($sizeOfId <= $sizeOfName){
    //not even data
    for($x=0; $x< $sizeOfId; $x++ ){
      $sql = "UPDATE tbl
              SET name = '".$sliptName[$x]."' 
              WHERE id = '".$sliptId[$x]."' ";
    }
    for($x=$sizeOfId; $x< $sizeOfName; $x++ ){
      $sql = "INSERT INTO tbl values(null,'".$sliptName[$x]."')";
    }
  }else{
    for($x=0; $x< $sizeOfName; $x++ ){
      $sql = "UPDATE tbl
              SET name = '".$sliptName[$x]."' 
              WHERE id = '".$sliptId[$x]."' ";
    }
  }