0

In order to insert some data to mysql I use:

$sql = "INSERT INTO MyGuests (fullname, email) VALUES ('John Doe', 'john@example.com')";

But I'd like, before that, if the fullname John Doe for example is already used in a query of MyGuests table then that to be updated with the e-mail. If not, then data to be inserted normally like above. How could I do that? Thanks a lot

Oti Na Nai
  • 1,327
  • 4
  • 13
  • 20

3 Answers3

0

You have to query MySQL first to check if there's any results already and if so run a UPDATE query instead of INSERT.

Alberto
  • 880
  • 5
  • 15
0

you can use on duplicate key update like this:

INSERT INTO MyGuests (fullname, email) VALUES ('John Doe', 'john@example.com') ON DUPLICATE KEY UPDATE email='john@example.com';

for this to work as expected make sure that fullname is the primary key.

Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
0

Just check rows using mysql num rows. Use the code below

$query = mysql_query("SELECT * FROM MyGuests WHERE fullname='John Doe'");
if(mysql_num_rows($query)==0){
mysql_query("INSERT INTO MyGuests (fullname, email) VALUES ('John Doe', 'john@example.com')");
}
else{
mysql_query("UPDATE MyGuests SET email='youremailname@name.com' WHERE fullname='John Doe'");
}

If you are using mysqli_* functions then replace mysql with mysqli. I am not using prepared statement , you have to use them to stop sql injection. I suggest you to use PDO or mysqli prepared statements to stop sql injection. Hope tis helps you

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38