Chek数组如果在DB中有ID则更新其他做插入

时间:2018-02-07 13:08:58

标签: php mysql arrays

我通过post发送具有相同名称的数组(内部ID)的输入值,如下所示

<form action="" method="POST" role="form" name="formetn" enctype="multipart/form-data">
  <input type="text" name="videolinks[<?php echo $videoid; ?>]" value="<?php echo $videolink; ?>" class="form-control">
</form

这里我得到数组并解析它

if(isset($_POST["hidden_input_name"]) && $_POST["hidden_input_name"]!="") 
{
  $ppp = $_POST['videolinks'];

  $arraylength = count($ppp);     //here i got count of sent items

  $ids = implode(",",array_keys($ppp));         //here I parse keys
  $escaped_values = array_map('mysql_real_escape_string', array_values($ppp));
  $values  = implode(",", $escaped_values);      //here I parse values
}

现在我需要检查我的表格中是否有相同的ID - &gt; 更新此行
如果是新ID - &gt; 插入此行

for($i = 0; $i < $arraylength; $i++)
{
  while($row = mysqli_fetch_array($selectvidelink))
  {
    $videoid  = $row["ID"];
  if ($videoid == key($ppp)) 
  {
   //do update of this row
  }
  else
  {
   //do insert of this row
  }
 }
}

我知道我做错了,但不知道我应该更改什么来检查数组。

2 个答案:

答案 0 :(得分:1)

<?php

if(isset($_POST["videolinksecret"]) && $_POST["videolinksecret"]!="" && ($_POST["videolinksecret"]) === "baisdbsdvSuvhs7634bHv73bnjonasecret")
{
$conn = connect_to_bd();
mysqli_set_charset($conn,"utf8");

//var_dump($_POST['videolinks']);

$fullarray = $_POST['videolinks'];

	foreach($fullarray as $key => $value) 
	{
		$query = "select * from videolink where id=$key";
		$pp = mysqli_query($conn,$query);
		if(mysqli_num_rows($pp)){
				$dd = "update videolink set `videolink`='$value' where id=$key";
		}
		else{
				$dd = "insert into videolink(`videolink`) values('$value')";
		}
		$videolinkupdate = mysqli_query($conn,$dd);
		//echo "$key is at $value";
	}
	if($videolinkupdate)
	{
		echo $alertx='<div class="alert alert-success alert-dismissible" id = "successupdate" role="alert">
				<button type="button" class="close" data-dismiss="alert" aria-label="Kapat"><span aria-hidden="true">&times;</span></button>
				<strong>Success!</strong>
	        </div>';
	}
		else
	{
		echo $alertx='<div class="alert alert-danger alert-dismissible" id = "successupdate" role="alert">
					<button type="button" class="close" data-dismiss="alert" aria-label="Kapat"><span aria-hidden="true">&times;</span></button>
					<strong>ERROR!</strong> ERROR 03! 
				</div>';
	}
	
}

<form action="" method="POST" role="form" name="formetn" enctype="multipart/form-data">
  <div class="col-sm-9">
    <input type="text" name="videolinks[<?php echo $videoid; ?>]" value="<?php echo $videolink; ?>" class="form-control">
  </div>
  <button type="submit" id="btnformetn" class="btn btn-md btn-success pull-right">Update</button>
</form>

答案 1 :(得分:0)

你最好在mysql端做这件事。获取有关insert on duplicate key update - https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

的更多信息