mysql - Updating the database using php -


i'm inserting addedworkhours database, problem if insert several times same id (afnumber), old , new values kept. new val doesn't replace old one. i'm trying update (the commented section) not @ successful. same result. i'm trying work using if/else condition, check whether value in column empty, insert. if not update, in if condition statement?

the way i'm getting updates output:

   if(isset($_post['submit'])){      if(addedwh null)          $addedhours = $_post['addedhours'];         $selectaf = $_post['selectaf'];               $sql1="insert `editedworkhours` (`afnumber`,`addedwh`) values('$selectaf','$addedhours')";               $getresult =mysql_query($sql1);              if(mysql_affected_rows() > 0)              {               }               else{               }      else                   $tempname = $row['field'];                 $sql2 = "update editedworkhours set addedwh ='".$_get["addedhours"]."' afnumber='".$_get["selectaf"]."'";                 $result2 = mysqli_query($con,$sql2);                 if ($con->query($sql2) === true) {                 } else {                     echo "error: " . $sql2 . "<br>" . $con->error;                     echo '<script>swal("error", "something went wrong '.$con->error.'", "error");</script>';                 }      echo '<script>swal("success", "changes have been saved", "success");</script>';     } end if; echo $menu; 

one elegant way of doing defining afnumber table's primary key:

alter table `editedworkhours`  add constraint `editedworkhours_pk` primary key (`afnumber`); 

edit:
gordon noted in comments, if have primary key, add unique constraint:

alter table `editedworkhours`  add constraint `editedworkhours_uc` unique (`afnumber`);     

once have constraint in place, can utilize mysql's insert's on duplicate key update clause:

insert `editedworkhours` (`afnumber`, `addedwh`) values ($selectaf, $addedwh) on duplicate key update `addedwh` = values(`addedwh`) 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -