I'm working on a project to add statistics for pageviews. I'm having trouble looking up and then storing in MySQL from PHP.
I have users stored in the database as:
ID Email_Address Visits
1 email@address.com NULL
2 email@address.com NULL
A variable is passed into the page called $ID which refers to which user has been visited.
Firstly, should the Visits column be a default of 0 rather than NULL?
Secondly, What query can I then use to go something like;
开发者_Go百科Lookup $ID, add 1 to Visits in that row. ie: Visits = Visits + 1? Also if $ID is blank, it shouldn't do anything.
Cheers
Yes, it should be default of 0
.
UPDATE `your-table`
SET `Visits` = `Visits` + 1
WHERE `ID` = :id
If the id
is blank, don't run the query.
Your views
column should probably default to zero.
Secondly, this is the query you should use:
update tablename set visits=visits+1 where id=:id
Replace tablename
with the name of your table and bind the value of :id
to the ID. (You are using prepared statements, right?) Also, if the ID is empty, just don't issue the query.
1) It really depends what you are trying to do. But, from what it looks like, I would default to 0 since it looks like a numeric field.
2) I don't want to write code for you, but I'll give you some links:
First you need to Select. Then add use the built in mysql PHP functions to add to views, then Update. Or you can do it all in one query. But, for beginners, I always advocate doing it in steps.
It also looks like ID is your primary key, which you shouldn't leave blank. Read about primary keys here.
精彩评论