0

So I'm trying to make a hit counter unique to each username.

I'm trying to make it so that if the username isn't in the database, it inserts the username into a field called username and inserts 1 as the amount of clicks into a thing called click.

If the username already exists, I want it to add one to the existing click value. I'm trying to make it case insensitive. However, it doesn't seem to work!

  $query = mysql_query("SELECT * FROM clicks WHERE username='$ytusernamecheck'");

  $numrows = mysql_num_rows($query);

  if ($numrows < 0)  
  {
      mysql_query("INSERT INTO clicks (username, clicks)
                                      VALUES ('$ytusernamecheck', 1)");
      echo $numrows;

  }
  else{}
Lion
  • 18,729
  • 22
  • 80
  • 110

3 Answers3

1

There are two mistakes in this line:

if ($numrows = '')  
  1. You are assigning (=), not comparing values (== or ===).

  2. mysql_num_rows() returns an integer, not an empty string.

Your final result should look like this:

if ($numrows === 0)  

FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    sorry i may be blind. where does he have if ($numrows='') – Drew May 26 '13 at 17:36
  • 1
    They editted their post after I posted my answer. It's annoying when they do that. – John Conde May 26 '13 at 17:36
  • anyone that is willing to say that an edit was made concerning a certain verbeage when it wasn't gets an upvote from me! so +1 as the correct answer – Drew May 26 '13 at 17:42
0

What you should probably do is create a unique index on username and instead use this;

-- first do: CREATE UNIQUE INDEX ix_clicks ON clicks(username);

INSERT INTO clicks VALUES ('username', 1)
  ON DUPLICATE KEY UPDATE clicks = clicks + 1;

It will do the insert/update in one operation without an extra query to the database.

An SQLfiddle to test with.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

Why not set a unique key on the username field and use this instead

mysql_query("INSERT INTO clicks (username, clicks) VALUES ('$ytusernamecheck', 1) 
on duplicate key update clicks=clicks+1");

Only 1 SQL statement to execute that way

dougis
  • 128
  • 10