简体   繁体   中英

insert if id does not exist or update table if id exist query?

hi can you help me to make my query update if table if id exist then if not insert it? here's my query:

if(isset($_POST['submit'])){

$a=$_POST['no1'];   $b=$_POST['ans1'];     $c=$_POST['det1'];
$d=$_POST['no2'];   $e=$_POST['ans2'];     $f=$_POST['det2'];
$g=$_POST['no3'];   $h=$_POST['ans3'];         $i=$_POST['det3'];
$j=$_POST['no4'];   $k=$_POST['ans4'];     $l=$_POST['det4'];
$m=$_POST['no5'];   $n=$_POST['ans5'];     $o=$_POST['det5'];
$p=$_POST['no6'];   $q=$_POST['ans6'];     $r=$_POST['det6'];
$s=$_POST['no7'];   $t=$_POST['ans7'];         $u=$_POST['det7'];
$v=$_POST['no8'];   $w=$_POST['ans8'];     $x=$_POST['det8'];
$y=$_POST['no9'];   z=$_POST['ans9'];      $zz=$_POST['det9'];
$aa=$_POST['no10']; $bb=$_POST['ans10'];       $cc=$_POST['det10'];

$sql=mysql_query("insert into bfp_personnel_questions `(`id`,`question_number`,`answer`,`details`) VALUES ('$id', '$a', '$b','$c'),   ('$id','$d','$e','$f'), ('$id','$g','$h','$i'), ('$id','$j','$k','$l'), ('$id','$m','$n','$o'), ('$id','$p','$q','$r'), ('$id','$s','$t','$u'), ('$id','$v','$w','$x'), ('$id','$y','$z','$zz'), ('$id','$aa','$bb','$cc')") or die(mysql_error());`

?><script>alert("Successfully Saved.");window.location="pds_1st.php?part=11";</script><?php }
}

尝试对重复键更新进行 SQL语法插入

First off, your script screams for prepared statements . You could drastically improve the speed and performance by switching (especially since you're using the obsolete mysql extensions).

I assume that id is a PRIMARY KEY or at least a UNIQUE index. The simplest way to do this is to do INSERT IGNORE , which will try to insert your record and, if they collide, ignores the error and moves on

INSERT INGORE INTO table(col1, col2)
VALUES('1', '2');

If you want to replace the values, you can use REPLACE in later versions of MySQL

REPLACE INTO table(col1, col2)
VALUES('1', '2');

If the key already exists, the row is updated.

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