Jump to content


This topic is now archived and is closed to further replies.


Update if exists or insert if doesn’t

Recommended Posts

Hey i need some help Refreshing my memory with some PHP

i have a form and that has 2 input box's lets say to keep it simple Name,Age and a sumit button

basically when the submit button is hit i need it to check if the Name(Primary Key) exist if it dosent insert it and if it dose exist and update the infomation wondering if it will be kinda like below


mysql_connect("localhost", "root", "####") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$result = mysql_query("SELECT Name FROM testDB where Name = 'alcoholic1' ") or die(mysql_error());

if  <> result.EOF then
   $result = mysql_query("UPDATE testD SET age='22' WHERE age='21'")
    or die(mysql_error());


   mysql_query("INSERT INTO testD
   (name, age) VALUES('Sandy Smith', '21' ) ")
   or die(mysql_error());

end if


Share this post

Link to post
Share on other sites
Something like this:

[code]$query = mysql_query("SELECT * FROM table WHERE name = 'blah'");
if (mysql_num_rows($query) == 0) {
   INSERT code here
} else {
   UPDATE code here

Or you could use the REPLACE MySQL command:
[a href=\"http://dev.mysql.com/doc/refman/5.0/en/replace.html\" target=\"_blank\"]http://dev.mysql.com/doc/refman/5.0/en/replace.html[/a]

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.