1

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 }
}
jcbbea
  • 17
  • 6
  • [Duplicate](http://stackoverflow.com/questions/6030071/mysql-table-insert-if-not-exist-otherwise-update). – ccKep Jan 10 '14 at 01:18
  • possible duplicate of [How to 'insert if not exists' in MySQL?](http://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql) – ccKep Jan 10 '14 at 01:24

2 Answers2

0

Try SQL syntax insert on duplicate key update.

petertc
  • 2,499
  • 20
  • 29
0

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.

Machavity
  • 28,730
  • 25
  • 78
  • 91