View Full Version : Adding +1 to mysql entrys.
WebmasterLULZ
12-04-2008, 01:55 AM
So how would i go about doing "if there was a result from selecting * from searches where keyword=abc add +1 to hit="
So if the field of "hit" has the value of 2 where the feild keyword is abc , then make it 3 (add a extra number).
Fou-Lu
12-04-2008, 01:57 AM
UPDATE table SET field = field + 1 WHERE keyword = 'abc'
WHERE can take any of the where clauses. Its the field = field + 1 that equates to an addition of one. This assumes numeric datatype of course.
I'll move this to the MySQL forum.
I may have mistaken you're criteria. Look into using a subquery on you're where clause to do a count. If count > 0 then perform the update.
WebmasterLULZ
12-04-2008, 02:12 AM
I dont need to do a if count >0 , i need to basically say.. if there was nothing found while selecting * from searches where keyword=abc then add abc under keywords. if abc already exists, then add +1 to how many times it's been searched.
Fou-Lu
12-04-2008, 02:29 AM
You'll need to use a REPLACE command, which fortunately MySQL does support.
I can't recall the exact syntax for this, and not sure how it will interact with the + 1, but it should work. I'm about 85% sure its the same syntax as an insert, except you use replace.
Another option would be to add a constraint for a key. You can add an on duplicate key constraint to perform the update instead of the insert.
Play with it a bit, I think if you do the field + 1 it will still work so long as the default value for you're number is 0.
Ludatha
12-04-2008, 05:42 PM
You posted this in the PHP section, so if you are using php:
function addStat($member, $type){
# Types: Posts, Comments, Love, Hits
$member = mysql_real_escape_string($member);
$type = mysql_real_escape_string($type);
# Secure the type and others just in case
$q = "SELECT * FROM users WHERE username = '$member'";
$q = mysql_query($q);
$q = mysql_fetch_array($q);
$newValue = $q[$type] + 1;
$q2 = "UPDATE users SET $type = '$newValue' WHERE username = '$member'";
$q2 = mysql_query($q2);
if(!$q2){
echo mysql_error();
}
}
Thats a snippet from my website, use it like:
addStat("nameOfMember", "hit");
Thats if its members etc. but you can edit the query's.
You can also use ++ to add one to the database, but that sometimes doesnt work.
vBulletin® v3.8.2, Copyright ©2000-2010, Jelsoft Enterprises Ltd.