If Record Exists, Update It. If Not, Insert It.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
WithHisStripes
Forum Contributor
Posts: 131
Joined: Tue Sep 13, 2005 7:48 pm

If Record Exists, Update It. If Not, Insert It.

Post by WithHisStripes »

I'm not sure how I would write a PHP statement that says "if a record with this value exists, then update it, if it doesn't, then insert it."

Can someone give me a hand? Thanks!
WithHisStripes
Forum Contributor
Posts: 131
Joined: Tue Sep 13, 2005 7:48 pm

Re: If Record Exists, Update It. If Not, Insert It.

Post by WithHisStripes »

Code: Select all

 
$sql = "SELECT COUNT(*) AS total FROM tableName WHERE recordName` = '$record'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$total = $row['total'];
 
if ($total == 1) {
} else {
}
 
Last edited by Benjamin on Mon May 11, 2009 6:00 pm, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: If Record Exists, Update It. If Not, Insert It.

Post by pickle »

Look up the REPLACE() statement. This can be done in MySQL without necessarily needing any PHP logic.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply