kirby
kirby

Reputation: 4041

Is there any way I can combine these two query statements?

I made a very simple view counter. Ultimately I will convert to a cronjob view counter/updater, but for now I will just use a mysql update query every time the page refreshes. I was wondering if there was any way to turn these 2 statements into one, trying to cut down on processing.

PHP:

$query=mysql_query("SELECT * FROM questions WHERE id='$q'");  //string is escaped (not shown)
while ($row=mysql_fetch_assoc($query)){
    $views=$row['views']+1;
}
mysql_query("UPDATE questions SET views='$views' WHERE id='$q'");

Also, it would be really helpful if you could point out potential security issues if you notice any. thanks

Upvotes: 0

Views: 40

Answers (2)

Sabari
Sabari

Reputation: 6335

I think you want to update the view everytime and increment with a value 1 . You can directly do it without select like :

mysql_query("UPDATE questions SET views=views+1 WHERE id='$q'");

This will increment your view .

Hope this helps :)

Upvotes: 1

Bruno Silva
Bruno Silva

Reputation: 3097

Why not just:

mysql_query("UPDATE questions SET views=views+1 WHERE id='$q'");

This will increase your views by 1.

Upvotes: 4

Related Questions