[SOLVED] i use UPDATE but i get an INSERTED row

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
andrei.mita
Forum Commoner
Posts: 65
Joined: Sun May 08, 2005 4:06 am
Location: Barlad/Romania

[SOLVED] i use UPDATE but i get an INSERTED row

Post by andrei.mita »

I'm building a simple counter using a mysql db. here is the code:

Code: Select all

<?php

mysql_connect("localhost", "root", "pass") or die(mysql_error());
mysql_select_db("promotie") or die(mysql_error());

//$_SERVER[REMOTE_ADDR];

$update = "UPDATE counter SET nr=1+nr WHERE ip ='".$_SERVER[REMOTE_ADDR]."'";
$result = mysql_query($update);

if (mysql_affected_rows($result) < 1)
{
$insert = "INSERT INTO counter (ip, nr) VALUES ('".$_SERVER[REMOTE_ADDR]."', 1)";
$result = mysql_query($insert);
$msg = "Welcome to CPP! This is your first visit from ".$_SERVER[REMOTE_ADDR];
echo $msg;
die();
}

$select = "SELECT * FROM counter WHERE ip ='".$_SERVER[REMOTE_ADDR]."' LIMIT 1";
$qur = mysql_query($select) or die(mysql_error());

$nr = mysql_fetch_assoc($qur);
$msg = "Welcome here for the ".$nr['nr']."th time!";

echo $msg;
?>
When I run the script on may local maschine all works fine but when I run it on a server, instead of updateing, another row is inserted BUT updated. instead of getting in the db one row like:
123.123.123.123 - 3

i get 3 like :
123.123.123.123 - 3
123.123.123.123 - 2
123.123.123.123 - 1

why is this happening? can you suggest something?
thanks.

Jcart | Please use

Code: Select all

tags when posting php. Review   [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

From the manual (http://www.php.net/mysql_affected_rows)

int mysql_affected_rows ( [resource link_identifier] )

thus the following will do what you expect from it ;)

Code: Select all

if (mysql_affected_rows() < 1)

You may also want to have a look at "REPLACE INTO" in the MySQL manual.
andrei.mita
Forum Commoner
Posts: 65
Joined: Sun May 08, 2005 4:06 am
Location: Barlad/Romania

Post by andrei.mita »

ohhh, damn this things agravate me. i understand now, thanks
Post Reply