Page 1 of 1

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

Posted: Sat May 28, 2005 11:55 am
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]

Posted: Sat May 28, 2005 1:22 pm
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.

Posted: Sun May 29, 2005 12:16 am
by andrei.mita
ohhh, damn this things agravate me. i understand now, thanks