View Full Version : if doesnt exist then create, else just update
04-24-2012, 09:14 PM
hello everyone, im curious as to how i would go about writing a script that would create a row if it doesnt already exist, but if it does exist then just update that row.
What would be the best way to do this?
04-24-2012, 09:33 PM
We need more information on what you're trying to do. Are you looking to match like a username or what? Thanks
04-24-2012, 09:35 PM
thanks for the reply.
it would need to be constructed like this:
if ($strTitle) doesnt exit in table create row, elseif it does exist uodate "views" +1 where pagename = $strTitle
04-25-2012, 09:06 AM
something like INSERT INTO ... ON DUPLICATE KEY UPDATE ... ?
04-25-2012, 09:09 AM
could you elaborate a little more please, maybe with a small example, as ive never used this before.
04-25-2012, 09:10 AM
a whole explanation (http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html)
04-25-2012, 09:12 AM
that is bang on exactly what i want :) thank you, ill report back with what i get and if it works or not :)
thanks once again :)
04-25-2012, 11:20 AM
ok, so ive looked into it, and ive wrote it like this, however, it neither inserts, nor updates :S
mysql_query("INSERT INTO pageviews (pagename,views) VALUES ($strTitle,0) ON DUPLICATE KEY UPDATE views=views+1");
have i gone wrong somewhere?
04-25-2012, 03:26 PM
ive tried the above mysql_query (from my previous post) on a couple of different pages, however i have still not managed to get it to work, any ideas why? am i doing it wrong?
04-26-2012, 05:45 PM
Hmm I believe you need single quotes in the values. I code these differently, but in this format, try:
mysql_query("INSERT INTO pageviews (pagename,views) VALUES ('$strTitle','0') ON DUPLICATE KEY UPDATE views=views+1");
04-26-2012, 06:48 PM
you need the quotes for the string value, integers are used without.
mysql_query("INSERT INTO pageviews (pagename, views) VALUES ('$strTitle', 0) ON DUPLICATE KEY UPDATE views=views+1");
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.