Jump to content


Photo

Update if exists or insert if doesn’t


  • Please log in to reply
1 reply to this topic

#1 alcoholic1

alcoholic1
  • Members
  • Pip
  • Newbie
  • 7 posts

Posted 31 May 2006 - 01:19 PM

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



<?php

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()); 

else

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


end if

php?>


#2 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 31 May 2006 - 02:37 PM

Something like this:

$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]
~ D Kuang




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users