mysql - SQL - IF EXISTS UPDATE ELSE INSERT INTO -


what i'm trying insert subscribers in database, if exists should update row, else insert into new row.

ofcourse connect database first , get $name, $email , $birthday url string.

$con=mysqli_connect("localhost","---","---","---"); // check connection if (mysqli_connect_errno())   {   echo "failed connect mysql: " . mysqli_connect_error();   }  $name=$_get['name'];  $email=$_get['email']; $birthday=$_get['birthday']; 

this works, adds new row;

mysqli_query($con,"insert subs (subs_name, subs_email, subs_birthday) values ('$name', '$email', '$birthday')");  mysqli_close($con); 

here's tried;

mysqli_query($con,"insert subs (subs_name, subs_email, subs_birthday) values '$name', '$email', '$birthday' on duplicate key update subs_name = values($name), subs_birthday = values($birthday)"); mysqli_close($con); 

and

mysqli_query($con,"if exists (select * subs subs_email='$email')     update subs set subs_name='$name', subs_birthday='$birthday' subs_email='$email' else     insert subs (subs_name, subs_email, subs_birthday) values ('$name', '$email', '$birthday')"); mysqli_close($con); 

and

mysqli_query($con,"if not exists(select * subs subs_email='$email') begin insert subs (subs_name, subs_email, subs_birthday) values ('$name', '$email', '$birthday') end"); mysqli_close($con); 

but none of them work, doing wrong?

any appreciated!

  1. create unique constraint on subs_email column, if 1 not exist:

    alter table subs add unique (subs_email) 
  2. use insert ... on duplicate key update:

    insert subs   (subs_name, subs_email, subs_birthday) values   (?, ?, ?) on duplicate key update   subs_name     = values(subs_name),   subs_birthday = values(subs_birthday) 

you can use values(col_name) function in update clause refer column values insert portion of insert ... on duplicate key update - dev.mysql.com

  1. note have used parameter placeholders in place of string literals, 1 really should using parameterised statements defend against sql injection attacks.

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -