RE: [PHP] PHP Add +1 mysql updates by 2?
| From: | Tommy Pham | Date: | Sat, 27 Nov 2010 04:45:53 +0000 |
| Subject: | RE: [PHP] PHP Add +1 mysql updates by 2? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-309697@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Tamara Temple [mailto:tamouse.lists@gmail.com]
> Sent: Friday, November 26, 2010 7:54 PM
> To: Richard West
> Cc: PHP General Mailing List
> Subject: Re: [PHP] PHP Add +1 mysql updates by 2?
>
>
> On Nov 26, 2010, at 8:36 PM, Richard West wrote:
>
> > Hey guys,
> > I've never run into this before.
> > I have a field in mysql for page views.
> > So I pull out value and do +1 to new value - after UPDATE SET it has
> > incremented by 2?
> >
> > $val = $row['a_downloads'] ;
> >
> > $new_val = $val+1;
> >
> > mysql_query("UPDATE cbn_articles SET a_downloads='$new_val' WHERE
> a_id
> > = '".$_GET['id']."' ");
> >
> > Any ideas? What am I missing?
> > RD
>
> a_downloads wouldn't happen to be an autoincrement value, would it?
>
IIRC, the auto_increment should only increment on an INSERT statement and
the field is omitted. Besides, in MySQL, auto_increment must also be part
of the primary key. From Richard's query, I'd say that his primary key
field is most likely a_id. IMO, the best way to count something is to set
the field to an int(eger) type. Then just run 'UPDATE table_name SET
count_field = count_field +1 WHERE criteria_column = $criteria'. This is
more safe as you many have simultaneous users downloading. This would
ensure an accurate count, whereas your logic wouldn't.
Regards,
Tommy
PS: Richard, you should validate and sanitize all inputs. Your query is
prone to injection attack (deletion of rows or your entire DB deleted). Use
either mysql_escape_string or, better yet, mysqli to prepare the statement
and bind the parameters.