Re: Subject: selecting and updating fields

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Why are you trying to do the job of the DBMS in script ? Try instead :

$query="SELECT nrviews FROM url WHERE url=".$url;
$result=mysql_query($query);
if (mysql_num_rows($result)==0) {
        $query="UPDATE url SET nrviews=nrviews+1 WHERE url='$url'";
} else {
        $query="INSERT INTO url (url,nrviews) VALUES ('$url',1);
}
mysql_query($query);

This gets the one or zero rows which conatin the unique URL, and does a second query which either updates the existing row by one hit, or inserts a new row with a value of 1 hit.

Cheers - Neil Smith.

At 17:39 12/10/2003 +0000, you wrote:
From: Claudiu Bandac <k@kgb.ro>
To: <php-db@lists.php.net>
Date: Sun, 12 Oct 2003 20:39:56 -0700
Message-ID: <20031012203956.107266@K>
Mime-Version: 1.0
Content-Type: text/plain; charset="iso-8859-1"
Subject: selecting and updating fields

Hi !

I've got a form that passes a variable to a script.
The script connects to a database and I need to check if a field containing that variable already exists in the table, and if it does, to select the "nr_of_views" field, increment it, and update the table and if it doesn't, to create a new field with that variable and set nr_of_views to 1


the table in my database that looks like this :
url                                                     nrviews
www.google.com                          1
www.yahoo.com                           3


And I've tried something like this:



$query = mysql_query("select * from url") or die (mysql_error());
while ($row = mysql_fetch_row($query))
{
if ($url === $row["url"])
{
$nrviews = $row["nrviews"];
$nrviews++
mysql_query("update url set nrviews='$nrviews' where url='$url'") or
die (mysql_error());
}
else
{
$nrviews=1;
mysql_query("insert into url (url, nrviews) values ('$url','$nrviews')") or
die (mysql_error());
}
}



AND STILL DOESN'T WORK !!!
When I get a variable that is not in the database, the whole thing goes crazy ! (it inserts lots of fields with that variable and nrviews=1



Please HELP !


Thank You !

-- PHP Windows Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Database Programming]     [PHP Install]     [Kernel Newbies]     [Yosemite Forum]     [PHP Books]

  Powered by Linux